You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/tasks/overview.mdx
+28-6Lines changed: 28 additions & 6 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -168,7 +168,7 @@ You can override this per-trigger by passing `ttl` in the trigger options, or se
168
168
169
169
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:
You can access the database client using `getDb()` in your tasks `run` function and all your hooks (global or task specific):
264
264
265
-
```ts
265
+
```typescript
266
266
import { getDb } from"./db";
267
267
268
268
exportconst myTask =task({
@@ -273,6 +273,28 @@ export const myTask = task({
273
273
});
274
274
```
275
275
276
+
#### Per-task middleware
277
+
278
+
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:
279
+
280
+
```typescript
281
+
import { task, locals } from"@trigger.dev/sdk";
282
+
283
+
const myLocal =locals.create<string>("myLocal");
284
+
285
+
exportconst myTask =task({
286
+
id: "my-task",
287
+
middleware: async ({ payload, ctx, next }) => {
288
+
locals.set(myLocal, "some-value");
289
+
awaitnext();
290
+
},
291
+
run: async (payload) => {
292
+
const value =locals.getOrThrow(myLocal);
293
+
// ...
294
+
},
295
+
});
296
+
```
297
+
276
298
### `onStartAttempt` function
277
299
278
300
<Info>The `onStartAttempt` function was introduced in v4.1.0</Info>
These lifecycle hooks allow you to run code when a run is paused or resumed because of a wait:
325
347
326
-
```ts
348
+
```typescript
327
349
exportconst myTask =task({
328
350
id: "my-task",
329
351
onWait: async ({ wait }) => {
@@ -466,15 +488,15 @@ Read more about `catchError` in our [Errors and Retrying guide](/errors-retrying
466
488
467
489
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.
468
490
469
-
```ts
491
+
```typescript
470
492
tasks.onCancel(({ ctx, signal }) => {
471
493
console.log("Run cancelled", signal);
472
494
});
473
495
```
474
496
475
497
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:
0 commit comments