trasherdk / serverless-mysql

A module for managing MySQL connections at SERVERLESS scale
MIT License
0 stars 0 forks source link

Snippet: Separete connection and handler #9

Open trasherdk opened 2 years ago

trasherdk commented 2 years ago

This could be used for connection to different database hosts, depending on different criteria, loading different config.

connection.js

const mysql = require('serverless-mysql')({
    library: require('mysql2'),
});

let globalConfig;

const initDb = async (dbConfig) => {
    globalConfig = dbConfig;
    mysql.config(dbConfig);
    mysql.connect();
};

const getDb = async () => {
    if (mysql.getClient() == null) initDb(globalConfig);
    return mysql;
};

const quitDb = async () => {
    await getDb().then(async (db) => {
        await db.end();
        db.quit();
    });
};

module.exports = {
    initDb,
    getDb,
    quitDb,
};

handler.js

const { initDb, getDb, quitDb } = require('../../../db/connection');
const { config } = require('../../../config/config');

exports.createHandler = async (event, context) => {
    ...
    const dbConfig = config.db[process.env.NODE_ENV];
    await initDb(dbConfig);
    const db = await getDb();

    // do multiple queries
    const rows = await db.query(...);
    const rows2 = await db.query(...);

    // before returning a response, close the connection
    await quitDb();
    return {
          statusCode: 201,
          ...
    };
}

Source: https://github.com/jeremydaly/serverless-mysql/issues/129#issuecomment-1126689866

Markkos89 commented 2 years ago

nice! thanks for sharing and referencing the source!

I was looking for this kind of solution for my app based on the nx-serverless monorepo