Kalim
Kalim

Reputation: 347

How to get request parameters within Model in Loopback

common/models/event.json

{
"name": "Event",
"mongodb": {
    "collection": "event"
},
"base": "PersistedModel",
"idInjection": true,
"options": {
    "validateUpsert": true
},
"http": {
    "path": "organizer/:organizer_id/events"
},
"properties": {},
"validations": [],
"relations": {},
"acls": [],
"methods": []
}

common/models/event.js

module.exports = function (Event) {

Event.disableRemoteMethod('upsert', true);
Event.disableRemoteMethod('exists', true);
Event.disableRemoteMethod('findOne', true);
Event.disableRemoteMethod('count', true);
Event.disableRemoteMethod('prototype.updateAttributes', true);

// Before get records put orgnaizerId in query
Event.observe('access', function (ctx, next) {
    var organizer_id = '';
    if (ctx.query.where) {
        ctx.query.where.organizerId = organizer_id;
    } else {
        ctx.query.where = {organizerId: organizer_id};
    }
    console.log(ctx.query);
    next();
});
}

in Access Operation hooks in event.js I want to get organizer_id parameter from the URL is defined in event.json like

"http": {
    "path": "organizer/:organizer_id/events"
}

in example URL look like example.com/organizer/54c88f62e4b0b0fca2d0f827/events/

How to do this?

Upvotes: 2

Views: 4407

Answers (1)

notbrain
notbrain

Reputation: 3396

Have you tried loopback.getCurrentContext()?

You have to enable it in config.json or config.ENV.js:

"remoting": {
  "context": {
    "enableHttpContext": true
  },
  ...
}

And then it should be available in your hook.

See http://docs.strongloop.com/display/JA/Using+current+context

Note: remoting.context option was removed in version 3.0. See http://loopback.io/doc/en/lb2/Using-current-context.html for more details.

Upvotes: 1

Related Questions