假设我有一个包含三个字段的表:“id”、“firstValue”和“secondValue”。我使用 postgres 作为其数据库。我想先添加一些计算,例如,第二个字段“firstValue”应该是(firstValue + SecondValue)/10。有谁知道如何在hooks服务中添加这个计算?有人可以给出 hooks 中的方法示例吗?
这是钩子(Hook)服务中的模板
module.exports = function () {
return async context => {
return context;
};
};
我将此文件保存为calculate.js
这是 hooks.js 中的模板
let calculate = require('./../../hooks/calculate');
module.exports = {
before: {
all: [],
find: [calculate()], // add some calculation
get: [calculate()], // add some calculation
create: [],
update: [],
patch: [],
remove: []
},
after: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
},
error: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
}
};
谢谢
最佳答案
context.result
是表示服务调用结果的对象(这里提到: https://docs.feathersjs.com/guides/basics/hooks.html ),可以在 after hooks 中访问它。那么你的钩子(Hook)应该是:
module.exports = function () {
return async context => {
context.result.computedField = ( context.result.firstValue + context.result.secondValue ) / 10
return context;
};
};
Hook 文件应该是:
let calculate = require('./../../hooks/calculate');
module.exports = {
before: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
},
after: {
all: [],
find: [calculate()],
get: [calculate()],
create: [],
update: [],
patch: [],
remove: []
},
error: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
}
};
关于node.js - 如何使用 Hook Feathers 在字段表中添加计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54251525/