$ open source · GPL-3.0 — need a commercial license? imqueue.com →

database() function

Connects to the database, loads the models, and returns the Sequelize instance.

Signature:

export declare function database(options?: IMQORMOptions): Sequelize;

Parameters

Parameter

Type

Description

options

IMQORMOptions

(Optional) Required on the first call, ignored on every later one.

Returns:

Sequelize

The single Sequelize instance for this process, with models registered.

Exceptions

TypeError when the first call has no options, or when no connection string can be resolved from either the options or the environment.

Remarks

A process-wide singleton. The first call does all the work; every call after it returns the cached instance and DOES NOT LOOK AT ITS ARGUMENT — so passing a different config later is silently ignored rather than reconnecting. That is why services can import database anywhere and call database(dbConfig) freely, and also why there is no way to swap the connection once it is up.

The first call resolves its configuration in this order:

  • connectionString, or DB_CONN_STR from the environment. Neither throws. - logger, or the @imqueue/rpc service default, or console. - sequelize.logging: left alone if explicitly falsy, so false disables logging; otherwise replaced with this package's formatter, honouring SQL_PRETTIFY and SQL_COLORIZE. A function you supply is wrapped rather than discarded, and receives the formatted SQL.

Models are then discovered by walking modelsPath for compiled .js files and taking the export whose name matches the filename — see IMQORMOptions.modelsPath, since a mismatch there fails in a way the error does not explain. The require is synchronous and CommonJS-scoped, which is what makes the models loadable from an ESM package.

Example

// config.ts — built once at start-up
export const dbConfig: IMQORMOptions = {
    logger,
    connectionString: process.env.DB_CONN_STR || '',
    sequelize: toSequelizeConfig(process.env.DB_CONN_STR, process.env.DB_DIALECT),
    modelsPath: './src/orm/models',
};

// anywhere in the service — the first call wins, the rest are free
const orm = database(dbConfig);