Working with Types
Typing the queues and runners will help prevent you from misusing Sidetrack, like inserting a job on a nonexistent queue, or inserting a job with an invalid payload. Following the types will improve your developer experience.
To get started, pass in the type for Sidetrack’s constructor. This type is an object with keys that match your queue names, and values that are the type of the payload for that queue. For example, if you have a queue called userOnboarding, and the payload is an object with an email property, you can type your queues like this:
type QueueNamesAndPayloads = {
userOnboarding: { email: string };
};
The type of your payload must only use JSON serializable values (unless using a payload transformer ), since the job payload will be persisted in the database in a column with the JSONB
datatype.
Here is the full example:
import { } from "sidetrack";
type = {
: { : string };
};
const = new <>({
: {
: .["DATABASE_URL"]!,
},
: {
: {
: async (, ) => {
.(`Welcome ${.}`);
},
},
},
});
Notice how the run function receives a job. This job contains a payload
key which will be typed to match your payload types above. The job also contains other fields you can use in your run function (e.g. the job’s id, scheduledAt, status, currentAttempt, etc.)
Avoiding errors
You can insert a job on only the userOnboarding queue. Notice the type error if I try inserting on a queue that doesn’t exist.
.("reports", { : "a@example.com" });
Types also prevent you from inserting a job with incorrect payload. Notice I must pass a email of type string.
.("userOnboarding", { phone: "11111111111" });
Reusable Types
Sidetrack exports most of the types it uses internally, so you can easily type your runners and queues. For example, if you have a queue called userOnboarding
, you can type your runner like this:
import { , } from "sidetrack";
type = {
: { : string };
};
const : <> = {
: {
: async (, ) => {
.(`Welcome ${.}`);
},
},
};
const = new <>({
: {
: .["DATABASE_URL"]!,
},
,
});
Notice how the SidetrackQueues
helper type lets you type your queues before you pass them in to the constructor, so you can also re-use them.