feature(collection): add BeforeRequest event#596
Conversation
New event that allows inspecting a request prior to the database being touched, and before every other event is executed. Allows canceling the request early (for example for authorization purposes), or modifying the query before it is executed by mongo depending on custom logic written in the event. Gives access to `me`, `ctx`, `event` (GET/PUT/POST/LOGIN/LOGOUT) variables in the event script. On PUT or POST, there are two additional variables available: `this` and `data` - containing the item being saved.
|
Example of a hard limit of 20 records per GET query: if (!me) cancel("Not authorized", 401); // don't allow anyone in that is not authorized
switch (event) {
case "GET":
if (!ctx.query.$limit || ctx.query.$limit > 20) ctx.query.$limit = 20; // max 20 results
break;
case "PUT":
// something for put
break;
case "POST":
// something for post
break;
} |
|
Also another example: Say instead of deleting a record entirely, you just set switch (event) {
case "GET":
ctx.query = ctx.query || {};
ctx.query.deleted = {$ne:true};
break;
} Previously, there was no good way to enforce this. If you did Let's not merge this for a few more days, as I'm still testing it so I might make small changes. I will leave a note here when I think it's fully ready. |
|
Alright, @ericfong: Been testing this for the past couple of weeks and it is stable on our end. If anything comes up, we can fix it later. It doesn't affect anything at all unless it is used. Add ?w=1 to the link for easier code reviewing: |
There was a problem hiding this comment.
var loginDomain = { event: "LOGIN" };
??
|
Great Thx! that is super useful for GET. Any guideline for using BeforeRequest with Validate in POST or PUT ? |
|
BeforeRequest does not replace Validate. It is still recommended to validate updates in the Validate event. You can do some checks inside BeforeRequest that apply to all of PUT/POST/DELETE if you need to, mostly for authorization purposes or other special requirements your scenario may require. |
|
Thanks for your contribution! |
|
Awesome! |
New event that allows inspecting a request prior to the database being touched, and before every other event is executed.
Allows canceling the request early (for example for authorization purposes), or modifying the query before it is executed by mongo depending on custom logic written in the event.
Gives access to
me,ctx,event(one of: GET, PUT, POST, LOGIN, LOGOUT) variables in the event script. You can use all thecancel()related methods and end the request right there.On PUT or POST, there are two additional variables available:
thisanddata- containing the item being saved.