node.js - 如何使用 Hook Feathers 在字段表中添加计算?
问题描述
假设我有一个包含三个字段的表,“id”、“firstValue”和“secondValue”。我使用 postgres 作为它的数据库。我想先添加一些计算,例如第二个字段“firstValue”应该是(firstValue + secondValue)/10。有谁知道如何在钩子服务中添加这个计算?有人可以在钩子中给出一个方法示例吗?
这是 hooks 服务中的模板
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中访问。那么你的钩子应该是:
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: []
}
};
推荐阅读
- azure - Azure Spot 实例 | gpu-集群
- nm - nm 结果在符号名称中带有尾随数字
- leakcanary - LeakCanary 报告 0 个不同的泄漏,但经常转储 hprof 文件
- python - 函数 if True 返回组合列表
- sonarqube - SonarQube 8.6 - 禁用某些语言的质量配置文件
- javascript - 从外部 json 文件中检索数据
- string - [FLUTTER]:根据 ListTile 的高度剪切文本
- javascript - 如何修复 Coinbase Pro API 请求标头?
- c - HTTP/1.1 服务器实现
- mysql - 如何为记录中不存在的条目分配零计数(mySQL 5.6)?