Search code examples
node.jspostgresqlknex.jspg

makes a database connection in the constructor using Knex


I am trying to implement knex connection below into an equivalent DB class. I searched but did not find any example implementation.

var knex = require('knex')({
  client: 'pg',
  connection: {
    host: '127.0.0.1',
    user: 'your_database_user',
    password: 'your_database_password',
    database: 'myapp_test'
  },
  pool: { min: 0, max: 7 }
})

Solution

  • let knex = require("knex");
    
    class Database {
       
       constructor(connection) {
          this.connection = connection;
       }
    
    
       connect(option = {}) {
         this.instance = knex(Object.assign(this.connection, option));
       }
    
    }
    
    
    let db = new Database({
        connection: {
           host: '127.0.0.1',
           user: 'your_database_user',
           password: 'your_database_password',
           database: 'myapp_test'
        }
    });
    
    db.connect({
      pool: { min: 0, max: 7 },
      client: 'pg'
    });