1.0.30 • Published 8 months ago

job-router v1.0.30

Weekly downloads
-
License
ISC
Repository
-
Last release
8 months ago

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

8 months ago

1.0.25

8 months ago

1.0.28

8 months ago

1.0.27

8 months ago

1.0.30

8 months ago

1.0.24

8 months ago

1.0.23

8 months ago

1.0.22

8 months ago

1.0.21

8 months ago

1.0.20

8 months ago

1.0.19

8 months ago

1.0.17

8 months ago

1.0.16

8 months ago

1.0.15

8 months ago

1.0.14

8 months ago

1.0.13

8 months ago

1.0.12

8 months ago

1.0.11

8 months ago

1.0.10

8 months ago

1.0.9

8 months ago

1.0.8

8 months ago

1.0.7

8 months ago

1.0.5

8 months ago

1.0.4

8 months ago

1.0.3

8 months ago

1.0.2

8 months ago

1.0.1

8 months ago

1.0.0

8 months ago