strongloop / strong-remoting

Communicate between objects in servers, mobile apps, and other servers.
www.strongloop.com
Other
105 stars 93 forks source link

Implementing async 'after' hook #422

Closed bitmage closed 7 years ago

bitmage commented 7 years ago

Yet another case of trying to implement caching. :-)

Caching has been mostly working and pretty stable for the last few months, with a solution like this:

app.remotes().before('Asset.expensiveOp', (ctx, next) => {
  const {res} = ctx
  // lookup in cache

  // if found, return it
  if (found) {
    res.send(result)

  // if not found, override send to receive the response
  } else {
    const send = res.send
    res.send = function(result) {
      cacheResult(result)
      send.call(this, result)
    }

    // then run the function
    next()
  }
})

I now want to get the id and timestamp that auto-generated for the cached object. So I'd like to do something like this:

      cacheResult(result)
        .then((cached) => send.call(this, cached))

However, overriding res.send with anything asynchronous won't work, because in Strong Remoting res.end is called immediately after res.send (Code Here).

Is there an existing after middleware that I'm missing that would work with an async operation? I'd prefer to stick to app.remotes() in order to keep this logic at a consistent layer. But just about anything would be better than monkey patching res.send. :-)

bitmage commented 7 years ago

I worked around this by not using loopback middleware at all, and instead implementing caching as a function wrapper.

Closing.