简体   繁体   English

销毁书架/knex 连接池

[英]Destroying bookshelf/knex connection pool

I have a db api that uses Bookshelf/Knex.我有一个使用 Bookshelf/Knex 的 db api。

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:我还有多个 api 操作调用,如下所示:

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.我的问题是 knex 池连接,我需要在解决操作文件中的请求之前销毁连接池。 However, in order to do that I need access to the bookshelf or knex objects which are imported in the model.但是,为了做到这一点,我需要访问模型中导入的书架或 knex 对象。

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.我可以在调用操作的顶级文件中创建 knex 对象,然后该进程可以在收到响应时破坏连接。 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?我怎样才能做到这一点,以便在不必到处传递 knex 对象的情况下销毁连接池?

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).我曾经遇到过这个问题,并通过将 knex 对象导出为书架导出的属性来解决它(即,将行module.exports.knex = knex;到书架的底部包括)。 That way, you can access is elsewhere by using bookshelf.knex.destroy() .这样,您可以使用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') ).对于书架没有实现您需要执行的某些查询的场合(例如bookshelf.knex.raw('Some unsupported SQL query') ),它也很方便。

This tutorial shows how to use knex.destroy() on APIs importing bookshelf.本教程展示了如何在 API 导入书架上使用knex.destroy()

On the bookshelf:书架上:

module.exports.knex = knex; module.exports.knex = knex;

On the API calling bookshelf:在 API 调用书架上:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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