简体   繁体   中英

Destroying bookshelf/knex connection pool

I have a db api that uses Bookshelf/Knex.

I have multiple Bookshelf models that look something like this:

import bookshelf from '../bookshelf';

var Product = bookshelf.Model.extend({
  tableName: 'product'
  // ...
});
export default Product;

The bookshelf include looks like :

import dbConfig from './dbConfig';

const knex = require('knex')(dbConfig);
const bookshelf = require('bookshelf')(knex);

module.exports = bookshelf;

I also have multiple api action calls that look something like this:

import Product from '../../Models/Product';

export default function getProducts(bookshelf) {

  return new Promise((resolve) => {

    Product.collection().fetch().then((products) => {
      resolve({
        products
      });
    });
  });
}

My problem is that knex pools connections and I need to destroy the connection pool before I resolve the request in the action files. However, in order to do that I need access to the bookshelf or knex objects which are imported in the model.

I can't think of a neat way of doing this. I could create the knex object in the top level file that calls the action, and then that process could destroy the connections when it receives the response. But then I would have to pass it to the actions and then to the models. How can I do this so that the connection pool is destroyed without having to pass the knex object around everywhere?

I came up against this once and solved it by exporting the knex object as a property of the bookshelf export (ie add the line module.exports.knex = knex; to the bottom of your bookshelf include). That way, you can access is elsewhere by using bookshelf.knex.destroy() . It can also be handy for occasions where bookshelf doesn't implement some query that you need to make (eg bookshelf.knex.raw('Some unsupported SQL query') ).

This tutorial shows how to use knex.destroy() on APIs importing bookshelf.

On the bookshelf:

module.exports.knex = knex;

On the API calling bookshelf:

const knex = require('./bookshelf').knex; 
...
Product.collection().fetch()
.then((products) => {
      resolve({
        products
      });})
.finally(() => { knex.destroy(); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM