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

After hook for find() not working properly in FeathersJS

我正在尝试解决 中描述的问题。

扩展提出了很多警告,我决定尝试 find() 的 after hook 并写了这个

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
    }})
  });
}

我在this post here的基础上使用了Promise.all

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

我错过了什么?

为了使函数 运行 正确,您实际上必须 return 一个 Promise,在您的情况下 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
    }})
  });
}

但是,Feathers 不会对该方法执行任何操作。只有方法 described in the service interface will be mapped to REST endpoints. Extending existing classes is described in the guide and the database adapter API 和扩展任何其他方法相同 JavaScript class.

另一种方法是使用 hook on the find method and set context.result