Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

use-orchestration-command.ts

42 lines1.4 KB

1import type {
2 AtomCommand,
3 AtomCommandOptions,
4 AtomCommandResult,
5} from "@t3tools/client-runtime/state/runtime";
6import {
7 AuthOrchestrationOperateScope,
8 EnvironmentAuthorizationError,
9 type EnvironmentId,
10} from "@t3tools/contracts";
11import * as Cause from "effect/Cause";
12import { AsyncResult } from "effect/reactivity";
13import { useCallback } from "react";
14​
15import { readEnvironmentScope } from "./session";
16import { useAtomCommand } from "./use-atom-command";
17​
18export const ORCHESTRATION_OPERATE_DENIED_MESSAGE =
19 "This connection cannot change threads or projects.";
20​
21export function useOrchestrationCommand<W extends { readonly environmentId: EnvironmentId }, A, E>(
22 command: AtomCommand<W, A, E>,
23 options?: string | AtomCommandOptions,
24): (value: W) => Promise<AtomCommandResult<A, E | EnvironmentAuthorizationError>> {
25 const run = useAtomCommand(command, options);
26 return useCallback(
27 async (value: W): Promise<AtomCommandResult<A, E | EnvironmentAuthorizationError>> => {
28 if (!readEnvironmentScope(value.environmentId, AuthOrchestrationOperateScope)) {
29 return AsyncResult.failure(
30 Cause.fail(
31 new EnvironmentAuthorizationError({
32 requiredScope: AuthOrchestrationOperateScope,
33 message: ORCHESTRATION_OPERATE_DENIED_MESSAGE,
34 }),
35 ),
36 );
37 }
38 return run(value);
39 },
40 [run],
41 );