假设我有一个包含三个字段的表:“ 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挂钩中进行访问。那么您的钩子应该是:

module.exports = function () {
    return async context => {
        context.result.computedField = ( context.result.firstValue + context.result.secondValue ) / 10

      return context;
    };
};


并且hooks文件应该是:

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

09-09 23:33