node.js - 如何使用 Hook Feathers 在字段表中添加计算?

标签 node.js hook feathersjs

假设我有一个包含三个字段的表:“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/

相关文章:

javascript - 尝试格式化日期,总是得到无效日期

node.js - AWS EC2 负载平衡 SSL Node JS - 我哪里出错了

javascript - 如何编写代码来测试 websocket 事件?

javascript - 将类转换为函数

node.js - AWS Elasticbeanstalk 在 PHP 实例类型中安装 Node 和 npm

node.js - 在 iOS 设备上进行 React native 部署卡在 Running 1 of 1 custom shell script

hook - TYPO3:创建或编辑页面后 Hook

C++如何替换一个函数但仍然使用原来的函数?

php - 如何在WordPress中设置动态 `home`和 `siteurl`?

node.js - 如何从钩子(Hook)访问 Mongoose 模型