如何使用钩羽在字段表中添加计算?

时间:2019-01-18 09:59:15

标签: node.js hook feathersjs

假设我有一个包含三个字段的表:“ id”,“ firstValue”和“ secondValue”。我使用postgres作为其数据库。我想先添加一些计算,例如,第二个字段“ firstValue”应为(firstValue + secondValue)/10。有人知道如何在hooks服务中添加此计算吗?有人可以用钩子举一个方法例子吗?

这是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: []
  }
};

谢谢

1 个答案:

答案 0 :(得分:1)

context.result是代表服务调用结果的对象(此处提到:https://docs.feathersjs.com/guides/basics/hooks.html),可以在之后的钩子中访问它。那么您的钩子应该是:

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: []
  }
};