Skip to content

Concept :: Database

Alex Tan Hong Pin edited this page Apr 25, 2018 · 2 revisions

To connect to the database, we define out connection to our desired database in database/index.js:

// src/database/index.js
import mysql from 'mysql2/promise'

async function Database ({ pool, host, user, database, password, port }) {
  // Use connection pool to avoid sudden termination of the connection
  const connection = mysql.createPool({
    connectionLimit: pool,
    host,
    user,
    database,
    password,
    port
  })

  return connection
}

export default Database

To use it:

import DB from './database'

async function main() {

  const db = await DB({
    pool: 10,
    host: 'localhost',
    user: 'root',
    database: 'example',
    password: '******',
    port: 3306
  })
  // Optionally, get the params from config
  // await DB(config.get('db'))
}
Clone this wiki locally