我让它与hapi-shelf一起工作,但我试图得到一个jsonapi响应,并且无法找到实现bookhelf-jsonapi-parms的方法,所以我正在尝试书架的原始包。 / p>
`TypeError:未捕获错误:Driver.fetchAll不是函数
server.js
'use strict';
const Hapi = require( 'hapi' );
const bodyParser = require( 'body-parser' );
const port = 9200;
const dbConfig = require( './config/config' );
const server = new Hapi.Server();
server.connection( {
port: port,
routes: {
cors: true
}
} );
var knex = require('knex')({
client: 'mysql',
connection: {
"host": "127.0.0.1",
"user": "user",
"password": "pass",
"database": "db"
}
});
server.bookshelf = require('bookshelf')(knex);
server.start( ( err ) =>{
if( err ){
throw err;
}
console.log( 'Server running on port ', port );
} );
module.exports = server;
require( './routes' );
模型/ driver.js
var bookshelf = require('../server').bookshelf;
module.exports = function (bookshelf) {
var Driver = bookshelf.Model.extend({
tableName: 'drivers'
});
return bookshelf.model('Driver', Driver);
};
控制器/ drivers.js
'use strict';
var server = require( '../server' );
var bookshelf = server.bookshelf;
var Driver = require('../models/driver');
exports.index = server.route(
{
method: 'GET',
path: '/drivers',
config: {
handler: function( request, reply ){
Driver.fetchAll().then( function( drivers ){
reply( drivers );
} )
}
}
}
);
答案 0 :(得分:4)
由于驱动程序模块正在返回函数,因此无法访问它。要访问Driver对象,您必须调用Driver函数,如下所示:
var Driver = require('../models/driver')(bookshelf)
我建议您更改下面的模型,因为使用您使用的方法,每次需要模块时,您都要初始化模型,这是不好的。
最好只使用以下设计初始化一次。
var Bookshelf = require('../server').bookshelf;
var Driver = Bookshelf.Model.extend({
tableName: 'drivers'
});
module.exports = Bookshelf.model('Driver', Driver);
在控制器中只需要如下所示。
var Driver = require('../models/driver')
Driver.fetchAll().then( function( drivers ){
reply( drivers );
})