Wiring up TypeORM with Serverless

Well, I’ve gotten as much system, app, and database design out of the way as I’m probably going to in order to get to our v1 launch of Roam. I’ve stood up our architecture in AWS and configured GraphQL API routes, like api.withroam.com/graphql.

The next step, IMO, should be to build out the database layer. I made the decision to go with managed Postgres, via AWS Aurora. As much as I like creating tables and managing connection states by hand, I’ve opted to go with a tried and true ORM called TypeORM.

Some benefits of TypeORM that I like:

  1. Typescript compatible: My plan is to use Typescript on entire Roam tech stack
  2. Eager and lazy relations: Can associate two tables easily and granularly
  3. Migrations: Intuitive migration engine out of the box
  4. Flexible: Works with many different database types just in case we switch one day
  5. Decorator pattern really easy to grasp
  6. Great logging engine built in


Setting up TypeORM in my Serverless project wasn’t completely straightforward since the project assumes that you’re running some semi-stateful architecture where your web server is always available. Specifically, it assumes you will only create a connection to the DB once and that after that call returns you the DB connection, that code path won’t be executed again.

That’s mostly true in Serverless, but it breaks down during local testing when you want to iterate fast and don’t necessarily want to tear down the connection every time.

So, I created a Database class that essentially lazy-initializes the connection. Here’s a gist:

My hope is that I can use this class to return a usable database connection regardless if the code is running Serverless or not, locally or not.