Search code examples
promisehookfeathersjs

After hook for find() not working properly in FeathersJS


I'm trying to solve the problem described in this question.

Extending presented so many caveats that I decided to try an after hook for find() and wrote this

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

I used Promise.all based on this post here.

But this is not working at all! When I perform a request GET http://localhost:3030/properties, which is the route for the service I am using, I just get the same old response, without the appended data I need.

What am I missing?


Solution

  • In order for the function to run properly you have to actually return a Promise, in your case the 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
        }})
      });
    }
    

    However, Feathers will not do anything with that method. Only the methods described in the service interface will be mapped to REST endpoints. Extending existing classes is described in the guide and the database adapter API and the same as extending any other JavaScript class.

    And alternative is to use a hook on the find method and set context.result.