Sanity Library Reference Docs
    Preparing search index...

    Type Alias DurableOperationsBeta

    The interface defining the durable operations available to a durable function. Using durables is considered experimental and may change in the future.

    type DurableOperations = {
        delegate<T>(
            name: {
                event?: unknown;
                handler: string | BlueprintResource<`sanity.function.${string}`>;
                name?: string;
                retry?: DurableRetryStrategy;
            },
        ): Promise<T>;
        fanout<T>(
            name: {
                branches: (
                    DurableStepFanoutHandler<T>
                    | DurableStepFanoutNamedHandler<T>
                )[];
                name?: string;
            },
        ): Promise<BatchResult<T>>;
        fanout<Branches extends readonly unknown[]>(
            name: { branches: Branches; name?: string },
        ): Promise<
            BatchResult<
                Branches[number] extends DurableStepFanoutHandler<ReturnType>
                    ? ReturnType
                    : Branches[number] extends DurableStepFanoutNamedHandler<ReturnType>
                        ? ReturnType
                        : never,
            >,
        >;
        run<T>(
            name: {
                handler: DurableStepRunHandler<T>;
                name?: string;
                retry?: DurableRetryStrategy;
            },
        ): Promise<T>;
        wait(name: { duration: DurableDuration; name?: string }): Promise<void>;
        waitForCallback<T>(
            __namedParameters: {
                name?: string;
                retry?: DurableRetryStrategy;
                submitter: DurableStepWaitForCallbackSubmitter;
                timeout?: DurableDuration;
            },
        ): Promise<T>;
        waitForCondition<T>(
            name: {
                initial: T;
                name?: string;
                next: DurableWaitForConditionNext<T>;
                poller: DurableWaitForConditionPoller<T>;
            },
        ): Promise<T>;
    }
    Index

    Methods

    • Invokes another function, of type durable or pubsub, and awaits its result. While awaiting, the durable function shuts down, so you are not charged for compute.

      Type Parameters

      • T

      Parameters

      Returns Promise<T>

      The value returned by the called function

      // my-delegated-function/index.ts
      export const handler = pubSubEventHandler(({event}) => {
      return 'yo'
      })

      // my-resource/index.ts
      export const handler = pubSubEventHandler(({event}) => {
      return 'hey'
      })

      // my-durable-function/index.ts
      export const handler = durableEventHandler(({step, context}) => {
      // With a function name
      const firstResult = await step.delegate({name: 'first-delegation', handler: 'my-delegated-function', event: {data: {hello: 'world'}}})
      // With a resource object
      const secondResult = await step.delegate({name: 'second-delegation', handler: context.resource.function('my-resource'), event: {data: {hello: 'world'}}})
      })
    • Runs a set of steps, or branches, in parallel. Each branch contains its own child durable context, with all usual step operations available. Branches may be named.

      Type Parameters

      • T

      Parameters

      Returns Promise<BatchResult<T>>

      A batch result of values returned or errors thrown by all branches.

      By using the generic, you can set a single, homogeneous return type for all branches.

      const results: BatchResult<string> = await step.fanout<string>({
      name: 'parallel-runs',
      branches: [async ({step, logger}) => {
      logger.log('Running first function in parallel')
      return 'first'
      }, {
      func: async ({step, logger}) => {
      logger.log('Running second function in parallel')
      return 'second'
      },
      name: 'second-branch',
      }],
      })
    • Runs a set of steps, or branches, in parallel. Each branch contains its own child durable context, with all usual step operations available.

      Type Parameters

      • Branches extends readonly unknown[]

      Parameters

      • name: { branches: Branches; name?: string }

        Step name

      Returns Promise<
          BatchResult<
              Branches[number] extends DurableStepFanoutHandler<ReturnType>
                  ? ReturnType
                  : Branches[number] extends DurableStepFanoutNamedHandler<ReturnType>
                      ? ReturnType
                      : never,
          >,
      >

      A batch result of values returned or errors thrown by all branches.

      This overload provides automatic type inference for heterogeneous branch return types. When branches return different types, the result will be BatchResult<T1 | T2 | ...>. Use the explicit type parameter overloads above for strict homogeneous type checking.

      const results: BatchResult<string | number> = await step.fanout({
      name: 'parallel-runs',
      branches: [async ({step, logger}) => {
      logger.log('Running first function in parallel')
      return 'first'
      }, async ({step, logger}) => {
      logger.log('Running second function in parallel')
      return 2
      }],
      })
    • Runs a named step. Its result is recorded, so if the durable re-runs the step is not executed again. Failures are retried on their own.

      Type Parameters

      • T

      Parameters

      Returns Promise<T>

      The value returned by the provided handler

      const hi = await step.run({
      name: 'run-step',
      handler: async ({logger}) => {
      logger.log('Running step')
      return 'hi'
      }})
      // With a retry config
      const hello = await step.run({
      name: 'run-with-retry'
      handler: () => {
      if (Math.random() > 0.5) throw new Error('random error!')
      return 'hello'
      }
      retry: { maxAttempts: 2, delay: { seconds: 5 } }
      })
    • Waits for a specified duration

      Parameters

      Returns Promise<void>

      Resolves after the duration

      Wait for 30 seconds

      await step.wait({name: 'wait30Sec', duration: { seconds: 30 }});
      

      Wait for 2 days and 3 hours

      await step.wait({name: 'waitALongTime', duration: { days: 2, hours: 3 }});
      
    • Generates a unique callback ID, runs a submitter function to pass the ID to an external system and waits for some external system to POST JSON data to a Sanity Durable callback API using the callback ID.

      Type Parameters

      • T

      Parameters

      Returns Promise<T>

      try {
      const successfulResult = await step.waitForCallback({name: 'ask-for-permission', submitter: async ({callbackId}) => {
      await sendForApproval(callbackId)
      }})
      } catch (e) {
      logger.log('oh no we received a callback failure', e)
      }
      @param name - Step name
      @param submitter - Function that submits the provided callbackId parameter to an external system
      @param timeout - Maximum time to wait for the callback result
      @param retry - retry configuration for the submitter function
      @returns The value returned to the Sanity Durable callback HTTP
    • Waits for a specified condition to be met by executing a poller method to retrieve state and then inspecting the retrieved state in a next method to determine whether to retry and after what delay to do so.

      Type Parameters

      • T

      Parameters

      Returns Promise<T>

      The value returned by the executed function

      await step.waitForCondition({{
      name: 'waitForCondition',
      initial: {
      article: null as Article | null,
      },
      poller: async (state, {attempt}) => {
      const client = createClient({
      apiVersion: '2026-08-05',
      ...context.clientOptions,
      })
      const article = await client.fetch<Article | null>(
      '*[_type == "article"][0]',
      )
      return {...state, article}
      },
      next: (state, {attempt}) => {
      if (state.article) return {shouldRetry: false}
      return {
      shouldRetry: true,
      delay: {
      seconds: Math.min(attempt * 2, 60),
      },
      }
      },
      },
      )