diff --git a/docs/tasks/overview.mdx b/docs/tasks/overview.mdx index b2bca9bc1e..8486cdb030 100644 --- a/docs/tasks/overview.mdx +++ b/docs/tasks/overview.mdx @@ -142,7 +142,7 @@ See our [maxDuration guide](/runs/max-duration) for more information. You can register global lifecycle hooks that are executed for all runs, regardless of the task. While you can still define these in the `trigger.config.ts` file, you can also register them anywhere in your codebase: -```ts +```typescript import { tasks } from "@trigger.dev/sdk"; tasks.onStart(({ ctx, payload, task }) => { @@ -236,7 +236,7 @@ tasks.onResume("db", async ({ ctx, payload, task }) => { You can access the database client using `getDb()` in your tasks `run` function and all your hooks (global or task specific): -```ts +```typescript import { getDb } from "./db"; export const myTask = task({ @@ -247,6 +247,28 @@ export const myTask = task({ }); ``` +#### Per-task middleware + +You can also define middleware per task by passing the `middleware` option in the task definition. This runs after global middleware and before the `run` function. Use it when only specific tasks need certain locals or setup: + +```typescript +import { task, locals } from "@trigger.dev/sdk"; + +const myLocal = locals.create("myLocal"); + +export const myTask = task({ + id: "my-task", + middleware: async ({ payload, ctx, next }) => { + locals.set(myLocal, "some-value"); + await next(); + }, + run: async (payload) => { + const value = locals.getOrThrow(myLocal); + // ... + }, +}); +``` + ### `onStartAttempt` function The `onStartAttempt` function was introduced in v4.1.0 @@ -297,7 +319,7 @@ export const taskWithOnStartAttempt = task({ These lifecycle hooks allow you to run code when a run is paused or resumed because of a wait: -```ts +```typescript export const myTask = task({ id: "my-task", onWait: async ({ wait }) => { @@ -440,7 +462,7 @@ Read more about `catchError` in our [Errors and Retrying guide](/errors-retrying You can define an `onCancel` hook that is called when a run is cancelled. This is useful if you want to clean up any resources that were allocated for the run. -```ts +```typescript tasks.onCancel(({ ctx, signal }) => { console.log("Run cancelled", signal); }); @@ -448,7 +470,7 @@ tasks.onCancel(({ ctx, signal }) => { You can use the `onCancel` hook along with the `signal` passed into the run function to interrupt a call to an external service, for example using the [streamText](https://ai-sdk.dev/docs/reference/ai-sdk-core/stream-text) function from the AI SDK: -```ts +```typescript import { logger, tasks, schemaTask } from "@trigger.dev/sdk"; import { streamText } from "ai"; import { z } from "zod"; @@ -502,7 +524,7 @@ export const interruptibleChat = schemaTask({ The `onCancel` hook can optionally wait for the `run` function to finish, and access the output of the run: -```ts +```typescript import { logger, task } from "@trigger.dev/sdk"; import { setTimeout } from "node:timers/promises";