Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
49 lines
1.7 KiB
TypeScript
49 lines
1.7 KiB
TypeScript
import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
|
|
import * as Cause from "effect/Cause";
|
|
import * as Option from "effect/Option";
|
|
import { AsyncResult, Atom } from "effect/reactivity";
|
|
|
|
const EMPTY_ASYNC_RESULT_ATOM = Atom.make(AsyncResult.initial<never, never>(false)).pipe(
|
|
Atom.withLabel("web-environment-query:empty"),
|
|
);
|
|
|
|
export interface EnvironmentQueryView<A, E = unknown> {
|
|
readonly data: A | null;
|
|
readonly dataUpdatedAt: number;
|
|
readonly error: string | null;
|
|
readonly failure: E | null;
|
|
readonly isPending: boolean;
|
|
readonly isSuccess: boolean;
|
|
readonly refresh: () => void;
|
|
}
|
|
|
|
export function formatEnvironmentQueryError(cause: Cause.Cause<unknown>): string {
|
|
const error = Cause.squash(cause);
|
|
return error instanceof Error && error.message.trim().length > 0
|
|
? error.message
|
|
: "The environment request failed.";
|
|
}
|
|
|
|
export function useEnvironmentQuery<A, E>(
|
|
atom: Atom.Atom<AsyncResult.AsyncResult<A, E>> | null,
|
|
): EnvironmentQueryView<A, E> {
|
|
const selectedAtom = atom ?? EMPTY_ASYNC_RESULT_ATOM;
|
|
const result = useAtomValue(selectedAtom);
|
|
const refresh = useAtomRefresh(selectedAtom);
|
|
return {
|
|
data: Option.getOrNull(AsyncResult.value(result)),
|
|
dataUpdatedAt:
|
|
result._tag === "Success"
|
|
? result.timestamp
|
|
: result._tag === "Failure"
|
|
? (Option.getOrNull(result.previousSuccess)?.timestamp ?? 0)
|
|
: 0,
|
|
error: result._tag === "Failure" ? formatEnvironmentQueryError(result.cause) : null,
|
|
failure:
|
|
result._tag === "Failure" ? Option.getOrNull(Cause.findErrorOption(result.cause)) : null,
|
|
isPending: atom !== null && result.waiting,
|
|
isSuccess: result._tag === "Success",
|
|
refresh,
|
|
};
|
|
}
|