stored-procedures - feathersjs sequelize 通过钩子调用存储过程无法解决
问题描述
我在创建一个调用存储过程的钩子时遇到问题。
我的自定义服务挂钩(customservice.hooks.js)是:
const callstored = require('../../hooks/callstored')
module.exports = {
before: {
all: [],
find: [callstored()],
get: [],
create: [],
update: [],
patch: [],
remove: []
},
...
我的服务类(customservice.class.js):
const mysql = require('mysql')
class Service {
constructor (options) {
this.options = options || {};
}
find (params) {
return Promise.resolve( [] );
}
get (id, params) {
return Promise.resolve({
id, text: `A new message with ID: ${id}!`
});
}
create (data, params) {
if (Array.isArray(data)) {
return Promise.all(data.map(current => this.create(current)));
}
return Promise.resolve(data);
}
update (id, data, params) {
return Promise.resolve(data);
}
patch (id, data, params) {
return Promise.resolve(data);
}
remove (id, params) {
return Promise.resolve({ id });
}
}
module.exports = function (options) {
return new Service(options);
};
module.exports.Service = Service;
我的服务(customservice.service.js):
const createService = require('./rankingvotes.class.js');
const hooks = require('./rankingvotes.hooks');
module.exports = function (app) {
const paginate = app.get('paginate');
const options = {
name: 'rankingvotes',
paginate
};
// Initialize our service with any options it requires
app.use('/rankingvotes', createService(options));
// Get our initialized service so that we can register hooks and filters
const service = app.service('rankingvotes');
service.hooks(hooks);
app.publish(() => {
});
};
最后我的钩子是(callstored.js)
const Sequelize = require('sequelize');
module.exports = function () {
return function (hook) {
sequelize = hook.app.get('sequelizeClient');
let result=[];
return sequelize.query('CALL RANKING();',{
nest: true,
raw: true }).then(function(response){
console.log(response[0]) //data are correct
hook.data=response[0];
return hook;
}).error(function(err){
console.log(err);
return hook;
});
}
}
如果我检查控制台,我得到了正确的数据,但没有从像 Postman 这样的 REST 客户端调用。
任何想法?谢谢你。
解决方案
如果要更改响应,则必须设置hook.result。
const Sequelize = require('sequelize');
module.exports = function () {
return async hook => {
try {
const sequelize = hook.app.get('sequelizeClient');
const response = await sequelize.query('CALL RANKING();',{
nest: true,
raw: true
});
console.log(response[0]) //data are correct
context.result = response[0];
} catch(error) {
console.error(error);
}
return hook;
}
}
hook.data是请求数据,仅适用于create
,update
和patch
。
请记住,如果在挂钩中设置,设置hook.result
将跳过您的自定义服务。find
before
推荐阅读
- c# - 防止更改 Web 服务 URL
- java - 排序数组到 BST
- mathematical-optimization - Apache Commons Math Optim:我应该使用 4.0 还是 3.6.1?4.0 似乎已死,但 3.6.1 已弃用……
- java - 使用 exec-maven-plugin 在我的 pom.xml 中运行 npm 命令
- python - 使用熊猫按不同列分组后,如何使用时间和数据列查找连续行的变化率?
- javascript - 从 Ext.tree.Panel 中获取选定的条目
- c++ - tao_idl -Gstl 不映射 std::string
- google-cloud-platform - 对于参考和参考信息,谷歌的基本技术有哪些?
- css - 根据道具长度反应样式宽度
- javascript - 从静态方法中创建实例