Skip to content

Commit 181866b

Browse files
committed
Add triggerAndWait().unwrap() to more easily get at the output or throw the subtask error
1 parent c738ef3 commit 181866b

File tree

3 files changed

+89
-34
lines changed

3 files changed

+89
-34
lines changed

.changeset/stale-actors-camp.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@trigger.dev/sdk": patch
3+
---
4+
5+
Add triggerAndWait().unwrap() to more easily get at the output or throw the subtask error

packages/trigger-sdk/src/v3/shared.ts

Lines changed: 72 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,40 @@ export type TaskRunResult<TOutput = any> =
263263
error: unknown;
264264
};
265265

266+
export class SubtaskUnwrapError extends Error {
267+
constructor(taskId: string, subtaskError: unknown) {
268+
if (subtaskError instanceof Error) {
269+
super(`Error in ${taskId}: ${subtaskError.message}`, { cause: subtaskError });
270+
this.name = "SubtaskUnwrapError";
271+
} else {
272+
super(`Error in ${taskId}`, { cause: subtaskError });
273+
this.name = "SubtaskUnwrapError";
274+
}
275+
}
276+
}
277+
278+
export class TaskRunPromise<T> extends Promise<TaskRunResult<T>> {
279+
constructor(
280+
executor: (
281+
resolve: (value: TaskRunResult<T> | PromiseLike<TaskRunResult<T>>) => void,
282+
reject: (reason?: any) => void
283+
) => void,
284+
private readonly taskId: string
285+
) {
286+
super(executor);
287+
}
288+
289+
unwrap(): Promise<T> {
290+
return this.then((result) => {
291+
if (result.ok) {
292+
return result.output;
293+
} else {
294+
throw new SubtaskUnwrapError(this.taskId, result.error);
295+
}
296+
});
297+
}
298+
}
299+
266300
export type BatchResult<TOutput = any> = {
267301
id: string;
268302
runs: TaskRunResult<TOutput>[];
@@ -311,7 +345,7 @@ export interface Task<TIdentifier extends string, TInput = void, TOutput = any>
311345
* }
312346
* ```
313347
*/
314-
triggerAndWait: (payload: TInput, options?: TaskRunOptions) => Promise<TaskRunResult<TOutput>>;
348+
triggerAndWait: (payload: TInput, options?: TaskRunOptions) => TaskRunPromise<TOutput>;
315349

316350
/**
317351
* Batch trigger multiple task runs with the given payloads, and wait for the results. Returns the results of the task runs.
@@ -512,20 +546,28 @@ export function createTask<
512546
customQueue
513547
);
514548
},
515-
triggerAndWait: async (payload, options) => {
549+
triggerAndWait: (payload, options) => {
516550
const taskMetadata = taskCatalog.getTaskManifest(params.id);
517551

518-
return await triggerAndWait_internal<TInput, TOutput>(
519-
taskMetadata && taskMetadata.exportName
520-
? `${taskMetadata.exportName}.triggerAndWait()`
521-
: `triggerAndWait()`,
522-
params.id,
523-
payload,
524-
{
525-
queue: customQueue,
526-
...options,
527-
}
528-
);
552+
return new TaskRunPromise<TOutput>((resolve, reject) => {
553+
triggerAndWait_internal<TInput, TOutput>(
554+
taskMetadata && taskMetadata.exportName
555+
? `${taskMetadata.exportName}.triggerAndWait()`
556+
: `triggerAndWait()`,
557+
params.id,
558+
payload,
559+
{
560+
queue: customQueue,
561+
...options,
562+
}
563+
)
564+
.then((result) => {
565+
resolve(result);
566+
})
567+
.catch((error) => {
568+
reject(error);
569+
});
570+
}, params.id);
529571
},
530572
batchTriggerAndWait: async (items) => {
531573
const taskMetadata = taskCatalog.getTaskManifest(params.id);
@@ -614,19 +656,27 @@ export async function trigger<TTask extends AnyTask>(
614656
* }
615657
* ```
616658
*/
617-
export async function triggerAndWait<TTask extends AnyTask>(
659+
export function triggerAndWait<TTask extends AnyTask>(
618660
id: TaskIdentifier<TTask>,
619661
payload: TaskPayload<TTask>,
620662
options?: TaskRunOptions,
621663
requestOptions?: ApiRequestOptions
622-
): Promise<TaskRunResult<TaskOutput<TTask>>> {
623-
return await triggerAndWait_internal<TaskPayload<TTask>, TaskOutput<TTask>>(
624-
"tasks.triggerAndWait()",
625-
id,
626-
payload,
627-
options,
628-
requestOptions
629-
);
664+
): TaskRunPromise<TaskOutput<TTask>> {
665+
return new TaskRunPromise<TaskOutput<TTask>>((resolve, reject) => {
666+
triggerAndWait_internal<TaskPayload<TTask>, TaskOutput<TTask>>(
667+
"tasks.triggerAndWait()",
668+
id,
669+
payload,
670+
options,
671+
requestOptions
672+
)
673+
.then((result) => {
674+
resolve(result);
675+
})
676+
.catch((error) => {
677+
reject(error);
678+
});
679+
}, id);
630680
}
631681

632682
/**

references/v3-catalog/src/trigger/simple.ts

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -31,15 +31,13 @@ export const fetchPostTask = task({
3131
export const anyPayloadTask = task({
3232
id: "any-payload-task",
3333
run: async (payload: any) => {
34-
const result = await tasks.triggerAndWait<typeof fetchPostTask>("fetch-post-task", {
35-
url: "https://jsonplaceholder.typicode.com/posts/1",
36-
});
34+
const { url, method } = await tasks
35+
.triggerAndWait<typeof fetchPostTask>("fetch-post-task", {
36+
url: "https://jsonplaceholder.typicode.comasdqdasd/posts/1",
37+
})
38+
.unwrap();
3739

38-
if (result.ok) {
39-
logger.info("Result from fetch-post-task 211111sss", { output: result.output });
40-
} else {
41-
logger.error("Error from fetch-post-task", { error: result.error });
42-
}
40+
console.log("Result from fetch-post-task 211111sss", { output: { url, method } });
4341

4442
return {
4543
payload,
@@ -126,10 +124,12 @@ export const parentTask = task({
126124

127125
await wait.for({ seconds: 5 });
128126

129-
const childTaskResponse = await childTask.triggerAndWait({
130-
message: payload.message,
131-
forceError: false,
132-
});
127+
const childTaskResponse = await childTask
128+
.triggerAndWait({
129+
message: payload.message,
130+
forceError: false,
131+
})
132+
.unwrap();
133133

134134
logger.info("Child task response", { childTaskResponse });
135135

0 commit comments

Comments
 (0)