首页 > 解决方案 > 如何使用 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: []
  }
};

谢谢

标签: node.jshookfeathersjs

解决方案


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

推荐阅读