如何处理 feathersjs 钩子内的承诺?

How to treat a promise inside a feathersjs hook?

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

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 数组的行。我还使用了 sequalize 搜索与存储在数组中的信息关联的对象。

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

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

如何 return 来自在 feathersjs 钩子内执行的承诺的数据?

您的 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;
  };
};