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

use-orchestration-command.ts

43 lines1.5 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​
21/** Recheck the target grant for every step of a thread or project mutation. */
22export function useOrchestrationCommand<W extends { readonly environmentId: EnvironmentId }, A, E>(
23 command: AtomCommand<W, A, E>,
24 options?: string | AtomCommandOptions,
25): (value: W) => Promise<AtomCommandResult<A, E | EnvironmentAuthorizationError>> {
26 const run = useAtomCommand(command, options);
27 return useCallback(
28 async (value: W): Promise<AtomCommandResult<A, E | EnvironmentAuthorizationError>> => {
29 if (!readEnvironmentScope(value.environmentId, AuthOrchestrationOperateScope)) {
30 return AsyncResult.failure(
31 Cause.fail(
32 new EnvironmentAuthorizationError({
33 requiredScope: AuthOrchestrationOperateScope,
34 message: ORCHESTRATION_OPERATE_DENIED_MESSAGE,
35 }),
36 ),
37 );
38 }
39 return run(value);
40 },
41 [run],
42 );