1.0.30 • Published 3 years ago
job-router v1.0.30
example
// event-schema.ts
type EventsSchema = {
"user.created": {
userId: string
}
};
// job-router.ts
const router = createJobRouter<EventsSchema>().on("user.created", [
router.createHandler(
"send verification email",
async ({ ctx, step, data: { userId, text } }) => {
const email = await step.run("send verification email", () =>
ctx.email.send({ userId, text })
);
await step.sleep(1, "day");
await step.run("check if email was verified", () =>
ctx.email.handleVerification(email)
);
}
),
]);
// scheduler.ts
// he we use SQS as our worker queue but you could use anything
import { SQSClient, SendMessageCommand } from "@aws-sdk/client-sqs";
const sqs = new SQSClient({});
const scheduler = createJobScheduler<EventsSchema>((job) =>
sqs.send(
new SendMessageCommand({
MessageBody: JSON.stringify(job),
QueueUrl: process.env.JOB_QUEUE_URL,
DelaySeconds: getDelaySeconds(job),
})
)
);
// sqs-worker.js
// a lambda function that processes the SQS queue
import { SQSHandler } from "aws-lambda";
const worker = createJobWorker<EventSchema>({
scheduler,
router,
createCtx: () => ({ analytics, email }),
});
export const handler: SQSHandler = async (event) => {
const jobs = event.Records.map((record) => JSON.parse(record.body));
await worker.handleMany(jobs);
};
// your-application.ts
scheduler.send("user.created", { userId: "123" });suggestions
- It's common for queues like SQS to guarantee at least once delivery, so keep your handlers idempotent in case the same event is run more than once
1.0.26
3 years ago
1.0.25
3 years ago
1.0.28
3 years ago
1.0.27
3 years ago
1.0.30
3 years ago
1.0.24
3 years ago
1.0.23
3 years ago
1.0.22
3 years ago
1.0.21
3 years ago
1.0.20
3 years ago
1.0.19
3 years ago
1.0.17
3 years ago
1.0.16
3 years ago
1.0.15
3 years ago
1.0.14
3 years ago
1.0.13
3 years ago
1.0.12
3 years ago
1.0.11
3 years ago
1.0.10
3 years ago
1.0.9
3 years ago
1.0.8
3 years ago
1.0.7
3 years ago
1.0.5
3 years ago
1.0.4
3 years ago
1.0.3
3 years ago
1.0.2
3 years ago
1.0.1
3 years ago
1.0.0
3 years ago