Skip to content

_findHandler, return data from post middleware, instead of the original result #188

@li5tun

Description

@li5tun

Is your feature request related to a problem? Please describe.
When I changed a field value(or add some other logic) in post, I want the changed object as the final result.

Describe the solution you'd like
return data instead of result

Describe alternatives you've considered
N

Additional context
`async function _findHandler(model, _id, request, Log) {
try {
let query = Object.assign({}, request.query)
try {
if (
model.routeOptions &&
model.routeOptions.find &&
model.routeOptions.find.pre
) {
query = await model.routeOptions.find.pre(_id, query, request, Log)
}
} catch (err) {
handleError(err, 'There was a preprocessing error.', Boom.badRequest, Log)
}

let flatten = false
if (query.$flatten) {
  flatten = true
}
delete query.$flatten
let mongooseQuery = model.findOne({ _id: _id })
mongooseQuery = QueryHelper.createMongooseQuery(
  model,
  query,
  mongooseQuery,
  Log
).lean()
let result = await mongooseQuery.exec()
if (result) {
  let data = result
  try {
    if (
      model.routeOptions &&
      model.routeOptions.find &&
      model.routeOptions.find.post
    ) {
      data = await model.routeOptions.find.post(request, result, Log)
    }
  } catch (err) {
    handleError(
      err,
      'There was a postprocessing error.',
      Boom.badRequest,
      Log
    )
  }
  if (model.routeOptions) {
    let associations = model.routeOptions.associations
    for (let associationKey in associations) {
      let association = associations[associationKey]
      if (association.type === 'ONE_MANY' && data[associationKey]) {
        // EXPL: we have to manually populate the return value for virtual (e.g. ONE_MANY) associations
        result[associationKey] = data[associationKey]
      }
      if (association.type === 'MANY_MANY' && flatten === true) {
        // EXPL: remove additional fields and return a flattened array
        if (result[associationKey]) {
          result[associationKey] = result[associationKey].map(object => {
            object = object[association.model]
            return object
          })
        }
      }
    }
  }

  if (config.enableSoftDelete && config.filterDeletedEmbeds) {
    // EXPL: remove soft deleted documents from populated properties
    filterDeletedEmbeds(result, {}, '', 0, Log)
  }

  Log.log('Result: %s', JSON.stringify(result))

  return result
} else {
  throw Boom.notFound('No resource was found with that id.')
}

} catch (err) {
handleError(err, null, null, Log)
}
}`

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions