Reusing the Database connection object with @vendia/serverless-express

Viewed 223

I want to use my existing ExpressJS code on Lambda functions and the @vendia/serverless-express seems to the right package.

I want to reuse the database connections between Lambda invocations. As per AWS docs and other blogs, it can be achieved by storing the connection object outside of the handler function. But I am not sure how to do it with the @vendia/serverless-express package.

They have the following example code: (can be found in their GH repo here)

const serverlessExpress = require('@vendia/serverless-express')
const app = require('./app')

let serverlessExpressInstance

function asyncTask () {
  return new Promise((resolve) => {
    setTimeout(() => resolve('connected to database'), 1000)
  })
}

async function setup (event, context) {
  const asyncValue = await asyncTask()
  console.log(asyncValue)
  serverlessExpressInstance = serverlessExpress({ app })
  return serverlessExpressInstance(event, context)
}

function handler (event, context) {
  if (serverlessExpressInstance) return serverlessExpressInstance(event, context)

  return setup(event, context)
}

exports.handler = handler

I can initialize the connection object in the asyncTask function. But, how do I make it available inside my app. (Express app) ?

0 Answers
Related