Last active
July 15, 2024 21:50
-
-
Save djfarrelly/ced8fcae2d47ccef1fb073fc9d35e913 to your computer and use it in GitHub Desktop.
Superjson Inngest Middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Superjson is awesome, but here are a few considerations for using transformers in middleware are: | |
1 - Building multi-language flows (TS + Python) become tricky if you're serializing events. | |
2 - You're locked into superjson for long running jobs, so if you want to change a serialization format, you'll have to support backcompat. | |
3 - Pass through TypeScript types for transformers like this aren't yet well supported. You may need to cast http://step.run return values until we fix that up (we plan to). | |
*/ | |
import { Inngest } from 'inngest'; | |
import { superjsonMiddleware } from './superjson-middleware'; | |
const inngest = new Inngest({ | |
id: 'demo-app', | |
middleware: [superjsonMiddleware] | |
}); | |
export default inngest.createFunction( | |
{ id: 'hello-world' }, | |
{ event: 'demo/event.sent' }, | |
async ({ event, step }) => { | |
// As of Inngest TS SDK v3.19.22 types modified via middleware | |
// do not pass through from the deserialization. | |
// To get around this, each return type must be cast "as" for types to work | |
// NOTE - This will be fixed in a future version | |
const result = await step.run('first', () => { | |
return { now: new Date() }; | |
}) as unknown as { now: Date} ; | |
console.log(result, typeof result.now, result.now instanceof Date); | |
const two = await step.run('second', () => { | |
return { later: new Date() }; | |
}); | |
return { | |
message: `Hello ${result.now} ${two.later}!`, | |
}; | |
} | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { InngestMiddleware } from 'inngest'; | |
import superjson from 'superjson'; | |
export const superjsonMiddleware = new InngestMiddleware({ | |
name: 'Superjson', | |
init() { | |
return { | |
onFunctionRun() { | |
return { | |
transformInput({ steps }) { | |
// Transform steps from Superjson to objects | |
const deserializedSteps = steps.map((step) => { | |
return { | |
...step, | |
data: superjson.deserialize(step.data), | |
}; | |
}); | |
return { | |
steps: deserializedSteps, | |
}; | |
}, | |
transformOutput({ result, step }) { | |
return { | |
result: { | |
data: superjson.serialize(result.data) | |
}, | |
}; | |
}, | |
}; | |
}, | |
}; | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment