Files
sign/packages/lib/jobs/client/trigger.ts

74 lines
2.0 KiB
TypeScript
Raw Normal View History

2024-05-15 18:55:05 +10:00
import { createPagesRoute } from '@trigger.dev/nextjs';
import type { IO } from '@trigger.dev/sdk';
import { TriggerClient, eventTrigger } from '@trigger.dev/sdk';
2024-05-22 21:57:05 +10:00
import type { JobDefinition, JobRunIO, SimpleTriggerJobOptions } from './_internal/job';
2024-05-15 18:55:05 +10:00
import { BaseJobProvider } from './base';
export class TriggerJobProvider extends BaseJobProvider {
private static _instance: TriggerJobProvider;
private _client: TriggerClient;
private constructor(options: { client: TriggerClient }) {
super();
this._client = options.client;
}
static getInstance() {
if (!this._instance) {
const client = new TriggerClient({
id: 'documenso-app',
apiKey: process.env.NEXT_PRIVATE_TRIGGER_API_KEY,
apiUrl: process.env.NEXT_PRIVATE_TRIGGER_API_URL,
});
this._instance = new TriggerJobProvider({ client });
}
return this._instance;
}
2024-05-22 21:57:05 +10:00
public defineJob<N extends string, T>(job: JobDefinition<N, T>): void {
2024-05-15 18:55:05 +10:00
this._client.defineJob({
id: job.id,
name: job.name,
version: job.version,
trigger: eventTrigger({
name: job.trigger.name,
schema: job.trigger.schema,
}),
run: async (payload, io) => job.handler({ payload, io: this.convertTriggerIoToJobRunIo(io) }),
});
}
2024-05-22 21:57:05 +10:00
public async triggerJob(options: SimpleTriggerJobOptions): Promise<void> {
2024-05-15 18:55:05 +10:00
await this._client.sendEvent({
2024-05-22 21:57:05 +10:00
id: options.id,
name: options.name,
payload: options.payload,
timestamp: options.timestamp ? new Date(options.timestamp) : undefined,
2024-05-15 18:55:05 +10:00
});
}
2024-06-17 16:59:14 +10:00
public getApiHandler() {
2024-05-15 18:55:05 +10:00
const { handler } = createPagesRoute(this._client);
return handler;
}
private convertTriggerIoToJobRunIo(io: IO) {
return {
wait: io.wait,
logger: io.logger,
2024-05-16 15:44:39 +10:00
runTask: async (cacheKey, callback) => io.runTask(cacheKey, callback),
2024-05-15 18:55:05 +10:00
triggerJob: async (cacheKey, payload) =>
io.sendEvent(cacheKey, {
...payload,
timestamp: payload.timestamp ? new Date(payload.timestamp) : undefined,
}),
} satisfies JobRunIO;
}
}