Introduction
In this post, we shall see how we can bundle Prisma using aws-lambda-nodejs with the CDK.
Prerequisites
This is a walkthrough of the steps required to bundle Prisma with CDK and so cloning the repo below and following along would be ideal.
ryands17 / prisma-lambda
Integrating Prisma with `aws-lambda-nodejs` to run Prisma on Lambda
Constructs
In this project, we have a simple Lambda function that uses Prisma to query data from a User
table and logs to the console. The only resource we create here is the Lambda function so let's look at that.
I'm skipping the imports in these snippets to make it smaller but if you want to view those you can check those out in the file mentioned in the comments.
// lib/prisma-lambda-stack.ts
new ln.NodejsFunction(this, 'prisma', {
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'handler',
entry: lambdaFn,
timeout: cdk.Duration.seconds(10),
environment: {
DB_URL: process.env.DB_URL || '',
},
bundling: {
nodeModules: ['@prisma/client', 'prisma'],
commandHooks: {
beforeBundling(inputDir: string, outputDir: string): string[] {
return []
},
beforeInstall(inputDir: string, outputDir: string) {
return [`cp -R ../prisma ${outputDir}/`]
},
afterBundling(inputDir: string, outputDir: string): string[] {
return [
`cd ${outputDir}`,
`yarn prisma generate`,
`rm -rf node_modules/@prisma/engines`,
]
},
},
},
})
Here, we create a simple Node.js Lambda function and the parameters like runtime
, handler
, entry
, timeout
and environment
are the basic Lambda parameters that we pass.
aws-lambda-nodejs
uses esbuild under the hood so your function is bundled using esbuild
. There are a couple of important parameters that we need to set for the bundling process.
The first is
nodeModules
. This will instructesbuild
to not include@prisma/client
andprisma
into our function file and treat them asnode_modules
.-
The other section to be configured is
commandHooks
. The main hooks we need here arebeforeInstall
andafterBundling
.- In
beforeInstall
, we run the commandcp -R ../prisma ${outputDir}/
. This makes sure we haveschema.prisma
present in the bundle. You can also directly copyschema.prisma
instead of the entire directory if you have themigrations
folder which is not required in the bundle. - The other hook we use is
afterBundling
. This is to generatePrismaClient
and to remove theengines
folder to reduce function size.
- In
The rest is a simple Prisma setup with a schema.prisma and a User
model.
Now when we run cdk synth
, the function will be bundled and ready for deployment.
Conclusion
So this is how we can package Prisma with aws-lambda-nodejs
.
Here is the repo again for those who haven't checked it out:
Top comments (1)
Curious which presentation tool you're using in this talk: youtube.com/watch?v=9zr6LHaMMYA the one in your browser on localhost, seems pretty cool.