代码之家  ›  专栏  ›  技术社区  ›  Ed de Almeida

find()的后钩子在FeathersJS中无法正常工作

  •  0
  • Ed de Almeida  · 技术社区  · 5 年前

    我正在努力解决中描述的问题 this question .

    扩展提出了太多的警告,所以我决定尝试使用后钩子 find() 写了这个

    async function findAdditionals(context) {
      const { result, app } = context;
      let newResultData = result.data.map(async pr => {
        let includedRecords = await app.service('propertyadds').find({
          query: {
            property_id: pr.id
          }
        })
        pr.additionals = includedRecords.map(e => e.additional_id);
        return pr;
      })
      Promise.all(newResultData).then(completed => {
        return Object.assign({},context,{result: {
          total: result.total,
          limit: result.limit,
          skip: result.skip,
          data: completed
        }})
      });
    }
    

    我曾经 Promise.all 基于 this post here .

    但这根本不起作用!当我执行请求时,获取 http://localhost:3030/properties ,这是我正在使用的服务的路由,我只得到相同的旧响应,没有需要的附加数据。

    我错过了什么?

    0 回复  |  直到 5 年前
        1
  •  2
  •   Daff    5 年前

    为了让函数正常运行,你必须 return 一个承诺,在你的情况下 Promise.all :

    async function findAdditionals(context) {
      const { result, app } = context;
      let newResultData = result.data.map(async pr => {
        let includedRecords = await app.service('propertyadds').find({
          query: {
            property_id: pr.id
          }
        })
        pr.additionals = includedRecords.map(e => e.additional_id);
        return pr;
      })
    
      return Promise.all(newResultData).then(completed => {
        return Object.assign({},context,{result: {
          total: result.total,
          limit: result.limit,
          skip: result.skip,
          data: completed
        }})
      });
    }
    

    然而,羽毛不会用这种方法做任何事情。只有方法 described in the service interface 将映射到REST端点。本文描述了对现有类的扩展 in the guide 还有 database adapter API 和扩展任何其他JavaScript类一样。

    另一种选择是使用 hook find 方法与集合 context.result .