Node.js 如何使用钩子在字段表中添加计算?
假设我有一个包含三个字段的表,“id”、“firstValue”和“secondValue”。我使用postgres作为它的数据库。我想先添加一些计算,例如,第二个字段“firstValue”应该是(firstValue+secondValue)/10。有人知道如何在hooks服务中添加此计算吗?有人能在hooks中给出一个方法示例吗 这是hooks服务中的模板Node.js 如何使用钩子在字段表中添加计算?,node.js,hook,feathersjs,Node.js,Hook,Feathersjs,假设我有一个包含三个字段的表,“id”、“firstValue”和“secondValue”。我使用postgres作为它的数据库。我想先添加一些计算,例如,第二个字段“firstValue”应该是(firstValue+secondValue)/10。有人知道如何在hooks服务中添加此计算吗?有人能在hooks中给出一个方法示例吗 这是hooks服务中的模板 module.exports = function () { return async context => {
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: []
}
};
感谢上下文。result是表示服务调用结果的对象(此处提到:),可以在after hook中访问它。那么你的钩子应该是:
module.exports = function () {
return async context => {
context.result.computedField = ( context.result.firstValue + context.result.secondValue ) / 10
return context;
};
};
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: []
}
};
钩子文件应该是:
module.exports = function () {
return async context => {
context.result.computedField = ( context.result.firstValue + context.result.secondValue ) / 10
return context;
};
};
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: []
}
};