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?
source share