3

I would like to first create a connection to my database (with mysql2) and then after that create a new Knex instance. I cannot find anything in the documentation about this. Is this even possible?

So, idealy I would like to do something like this (simplified version):

const mysql = require('mysql2');
const Knex = require('knex');

const connection = mysql.createConnection(connectionConfig);
await connection.connect();
const knex = new Knex({
    client: 'mysql2',
    connection: connection,
}):
Terrabythia
  • 2,031
  • 3
  • 19
  • 29
  • What is the reason for this? – felixmosh Dec 17 '20 at 18:08
  • @felixmosh It has to do with dependency injection, scoped config (the knex and mysql modules are two different modules in my team's project) and some preferred setup from my part. It's not that I cannot get it working otherwise, but this would be my preferred setup. – Terrabythia Dec 18 '20 at 08:10

1 Answers1

8

There is no way to initialize whole knex with connection outside, but you can pass existing connection to knex like:

const mysql = require('mysql2');
const Knex = require('knex');

const connection = mysql.createConnection(connectionConfig);
await connection.connect();

const knex = Knex({
  client: 'mysql2'
});

// this is documented in knex docs
const res = await knex('table').connection(connection).where('id', 1);

Mikael Lepistö
  • 18,909
  • 3
  • 68
  • 70