A remote hook is a function that's executed before or after a remote method.
Get the app (in the state following the last article) from GitHub and install all its dependencies:
$ git clone https://github.com/strongloop/loopback-getting-started-intermediate.git $ cd loopback-getting-started-intermediate $ git checkout step4 $ npm install
Introducing remote hooks
Recall in Extend your API, you created a remote method—a custom function that you can call through a REST endpoint. A remote hook is simply a function that gets executed before or after the remote method.
You can define two kinds of remote hooks:
beforeRemote()
runs before the remote method.afterRemote()
runs after the remote method.
In both cases, you provide two arguments: a string that matches the remote method you want to which you want to "hook" your function, and a callback function. Much of the power of remote hooks is that the string can include wildcards, so it is triggered by any matching method.
Create the remote hook
Here, you're going to define a remote hook on the review model, specifically Review.beforeRemote
.
Modify
common/models/review.js
, and add the following code:
module.exports = function(Review) { Review.beforeRemote('create', function(context, user, next) { var req = context.req; req.body.date = Date.now(); req.body.publisherId = req.accessToken.userId; next(); }); };
This function is called before a new instance of the Review model is created. The code:
- Inserts the
publisherId
using the access token attached to the request. - Sets the date of the review instance to the current date.
I assume you could use a beforeCreate model hook to do the same thing?
It might be instructive to show how this would be accomplished or at least mention it.
@rand Yeah, but it's more hairy I think since we don't have access to the `req` object there. We need to it get a handle on the `accessToken`. I believe we have something called `loopback.context` or something now so we can get context that way in a model hook, but I have tried this myself yet. -simon