如何在Sails js应用程序中全局使用knexjs

问题描述 投票:2回答:2

如果不使用水线,如何在控制器或任何其他模型文件中获取knex对象。

例如:在我的api / models / Users.js中

module.exports = {
     find : function(id){
         // my knex query
     },
     insert : function(data){
         // my knex query again   
     } 
}

所以在我的控制器中,我会做:

var result = Users.find(id);

var result = Users.insert({username : 'sailsjs'});

或knex对象将在全球范围内可用,而不会在模型文件本身中使用...因此,我可以在控制器自身中进行knex查询

// UsersController / index

index : function(req, res){
      // my knex query
}

谢谢阿里夫

node.js global-variables sails.js waterline knex.js
2个回答
3
投票

// config / bootstrap.js

module.exports.bootstrap = function (cb) {

    var Knex  = require('knex');
    var knex = Knex.initialize({
        client : "mysql",
        connection : {
            host :'localhost',
            user :'root',
            database : 'sales_force',
            password : '*******'
        }
    });
    knex.instanceId = new Date().getTime();

    sails.config.knex = knex;

  // It's very important to trigger this callack method when you are finished 
  // with the bootstrap!  (otherwise your server will never lift, since it's waiting on the bootstrap)
  cb();
};

//在控制器中

var knex = sails.config.knex

这将返回knex对象。 knex.instanceId显示相同的连接被全部使用。

请建议是否可能引起任何问题。

谢谢阿里夫


0
投票

在Sails Js(测试版本1+)中全局使用Knex Js的最佳选择是在配置目录中创建一个名为knex.js的文件,如下所示:

/**
 * Knex Js, Alternate DB Adapter, In case needed, it is handy for doing migrations
 * (sails.config.knex)
 *
 *
 * For all available options, see:
 * http://knexjs.org/
 */

const developmentDBConfig = require('./datastores');
const stagingDBConfig = require('./env/staging');
const productionDBConfig = require('./env/production');


function getConnectionString() {
  let dbConnectionString = developmentDBConfig.datastores.default.url;

  if (process.env.NODE_ENV === 'staging') {
    dbConnectionString = stagingDBConfig.datastores.default.url;
  }

  if (process.env.NODE_ENV === 'production') {
    dbConnectionString = productionDBConfig.datastores.default.url;
  }

  return dbConnectionString;
}


module.exports.knex = require('knex')({
  client: 'postgresql',
  connection: getConnectionString()
});

现在,在任何文件中,您都可以设置knex并将其用作:

// Now use this knex object for anything like:
let user = await sails.config.knex('user').select('*').first();
© www.soinside.com 2019 - 2024. All rights reserved.