Insert a job within a transaction
One huge advantage of being a database-backed library is that we can insert jobs transactionally! This means that if you are in the middle of a transaction and your transaction fails, your job will be rolled back.
For example, say your application logic wants to send a email once a user is created. Here’s a Prisma example to insert a job transactionally with Sidetrack’s usePrisma
function:
import { } from "@prisma/client";
import { } from "sidetrack";
import { } from "@sidetrack/client-prisma";
const = new ();
const = new <{
: { : string };
}>({
: {
: .["DATABASE_URL"]!,
},
: {
: {
: async () => {
.(`Welcome ${..}`);
},
},
},
});
// In this transaction, we're creating both the user and background job
.$transaction(async () => {
const = await .user.create(/* create your user */);
return .(
"userOnboarding",
{
: .email,
},
{ : () },
);
});
// if you run other application code which fails, the entire transaction will rollback
// and neither the job nor user will be inserted!
.$transaction(async () => {
const = await .user.create(/* create your user */);
await .(
"userOnboarding",
{
: .email,
},
{ : () },
);
throw new ("Something went wrong");
});