Serverless-offline: Singleton issue with typeorm and serverless-offline

Created on 4 Aug 2018  路  4Comments  路  Source: dherault/serverless-offline

Hoping someone might have a solution to this.

I have a db connection class using typeorm which acts as a singleton, by setting a variable outside the class. Whenever attempting to connect to the database, it checks to see if it already has a connection and reuses it or creates a new one. On the deployed lambda this works, because the container persists and will reuse the connection.

With serverless-offline, the state is not saved in between runs it loses the variable and attempts to connect again (typeorm errors out because it's trying to reuse the name, so something is being saved somewhere.) Has anyone run into this or have a workaround to work offline?

     import { Connection, createConnection } from 'typeorm';

    // a connection singleton.
    let dbConnectionPromise: Promise<Connection>;

    export default class Database {


      getDb() {
       if (dbConnectionPromise) {
          return dbConnectionPromise;
       }
       const credentials = require(Database.getCredentials());

       dbConnectionPromise = createConnection(credentials);

       return dbConnectionPromise;
      }

Most helpful comment

Hi @ktwbc , try using the --skipCacheInvalidation option

All 4 comments

Hi @ktwbc , try using the --skipCacheInvalidation option

FYI
Naming each connection randomly when running locally solves the issue for me

I am using typeorm with nestjsand serverless-webpack. In that case --skipCacheInvalidation is not a solution since it messes up with webpack.

In last resort you can use --useSeparateProcesses to have a complete separation of your lambda calls.
But it changes some of the behavior of the emulation.

Please note, that in new version of serverless-offline --skipCacheInvalidation does not exist use --allowCache instead

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ghost picture ghost  路  4Comments

aldofunes picture aldofunes  路  3Comments

conradoramalho picture conradoramalho  路  3Comments

Ali-Dalal picture Ali-Dalal  路  4Comments

Looveh picture Looveh  路  4Comments