How to provide a Knex connection in nodejs

I am using NodeJS, Express and MySQL for my project and want to use ORM with a bookshelf.

The bookshelf uses Knex for querying, modeling and offers to establish a DB connection through Knex ( http://bookshelfjs.org/#installation ).

I am having trouble installing a successful database connection with Knex. I want to start the server only if the connection to the database is successful, but it seems that it does not offer anything after the connection is established for this (no promises or properties).

This is the code I used.

import _knex from "knex"; // npm install knex --save import _bookshelf from "bookshelf"; // npm install bookshelf --save let knex = _knex({ client: "mysql", connection: { host: "127.0.0.1", database: process.env.DB, user: process.env.DB_USERNAME, password: process.env.DB_PASSWORD }, debug: true }); let bookshelf = _bookshelf(knex); module.exports.knex = knex; module.exports.bookshelf = bookshelf; 

Additional reference: There is another ORM called Sequelize and it provides sequelize.authenticate() which return Promise and can be used as ( http://docs.sequelizejs.com/en/latest/api/sequelize/#authenticate-promise )

 sequelize.authenticate() .then( () => { console.log("Db successfully connected"); app.listen(port, () => console.log(`App started at: ${port}`) ); }) .catch( err => console.log('Unable to connect to the database') ); 

The only solution I can think of is to execute a raw query like USE {DB_NAME} and use its output to decide whether to start the server or not. Is this solution good enough?

+5
source share
1 answer

This was discussed earlier this week in knex magazine. https://github.com/tgriesser/knex/issues/1886

Querying is a good way to check if you can connect to the database. If there are no requests, the pool does not necessarily create any initial connections (depending on the pool settings).

You can also connect the afterCreate pool afterCreate to notify you when an ever new connection has made to the database ( https://github.com/knex/documentation/pull/17/files ).

+4
source

Source: https://habr.com/ru/post/1263689/


All Articles