【问题标题】:How to treat a promise inside a feathersjs hook?如何在 feathersjs 钩子中处理承诺?
【发布时间】:2017-12-08 21:46:33
【问题描述】:

我想在插入数据库之前验证数据。 Feathersjs 的方式是使用钩子。在插入权限组之前,我必须考虑用户帖子提供的数据的完整性。我的解决方案是找到与用户提供的数据相关的所有权限。通过比较列表的长度,我可以证明数据是否正确。钩子的代码贴在下面:

const permissionModel = require('./../../models/user-group.model');

module.exports = function (options = {}) { 
  return function usergroupBefore(hook) {
    function fnCreateGroup(data, params) {
      let inIds = [];
      // the code in this block is for populating the inIds array

      if (inIds.length === 0) {
        throw Error('You must provide the permission List');
      }
      //now the use of a sequalize promise for searching a list of
      // objects associated to the above list
      permissionModel(hook.app).findAll({
         where: {
          id: {
            $in: inIds
          }
       }
      }).then(function (plist) {
        if (plist.length !== inIds.length) {
          throw Error('You must provide the permission List');
        } else {
          hook.data.inIds = inIds;
          return Promise.resolve(hook);
        }
      }, function (err) {
        throw err;
      });
    }

    return fnCreateGroup(hook.data);
  };
};

我注释了处理其他参数的某些信息以填充inIds 数组的行。我还对与存储在数组中的信息关联的对象进行了均衡搜索。

then 块内的这个块在后台执行。在 feathersjs 控制台上显示结果

但是,数据已插入数据库。

如何从在 feathersjs 钩子中执行的承诺返回数据?

【问题讨论】:

    标签: node.js promise feathersjs feathers-sequelize feathers-hook


    【解决方案1】:

    您的fnCreateGroup 没有返回任何内容。你必须return permissionModel(hook.app).findAll。或者,如果您使用的是 Node 8+,async/await 将使这更容易理解:

    const permissionModel = require('./../../models/user-group.model');
    
    module.exports = function (options = {}) { 
      return async function usergroupBefore(hook) {
        let inIds = [];
        // the code in this block is for populating the inIds array
    
        if (inIds.length === 0) {
          throw Error('You must provide the permission List');
        }
    
        //now the use of a sequalize promise for searching a list of
        // objects associated to the above list
        const plist = await permissionModel(hook.app).findAll({
            where: {
            id: {
              $in: inIds
            }
          }
        });
    
        if (plist.length !== inIds.length) {
          throw Error('You must provide the permission List');
        } else {
          hook.data.inIds = inIds;
        }
    
        return hook;
      };
    };
    

    【讨论】:

    • 我正在将节点 6 更新到节点 8 安装。谢谢
    猜你喜欢
    • 2016-09-06
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 2017-03-26
    • 2021-04-10
    • 2020-04-11
    • 1970-01-01
    • 2021-12-19
    相关资源
    最近更新 更多