1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Ensure Lookup Can Be Retried as an Inngest TIL

This commit is contained in:
jbranchaud
2024-04-26 23:26:51 -05:00
parent e974a184c6
commit 41f5b526d2
2 changed files with 59 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1420 TILs and counting..._ _1421 TILs and counting..._
--- ---
@@ -410,6 +410,7 @@ _1420 TILs and counting..._
### Inngest ### Inngest
- [Ensure Lookup Can Be Retried](inngest/ensure-lookup-can-be-retried.md)
- [Exit Function Early Without Retries](inngest/exit-function-early-without-retries.md) - [Exit Function Early Without Retries](inngest/exit-function-early-without-retries.md)
### Internet ### Internet

View File

@@ -0,0 +1,57 @@
# Ensure Lookup Can Be Retried
A common thing to do in a workflow step is to look up a record. This might be a
record that was created or updated around the time that the workflow was
triggered.
You need to be sure the record was found before proceeding. That might end up
looking like this:
```typescript
export default inngest.createFunction(
{ id: "record-user-purchase" },
{ event: "app/record.purchase" },
async ({ event, step }) => {
const checkoutSession =
await step.run("find checkout session", async () => {
const cs = provider.lookupSession(event.checkoutSessionId)
return cs;
});
if(!checkoutSession) {
throw new Error('Checkout session not found')
}
}
);
```
This approach has a subtle problem which is that the error for a missing
checkout session is raised _outside_ the step that sets `checkoutSession`. As
inngest does a series of retries, the memorized `checkoutSession` step won't be
rerun and the error will continue to be thrown.
It is better to raise the error _within_ the lookup step:
```typescript
export default inngest.createFunction(
{ id: "record-user-purchase" },
{ event: "app/record.purchase" },
async ({ event, step }) => {
const checkoutSession =
await step.run("find checkout session", async () => {
const cs = provider.lookupSession(event.checkoutSessionId)
if(!cs) {
throw new Error('Checkout session not found')
}
return cs;
});
}
);
```
If the checkout session is missing on the first couple tries, the step will
have a chance to retry the lookup and maybe eventually find what it is looking
for.