node-restful
node-restful copied to clipboard
Selecting entries for one user?
Hi,
Great library!
I wondered if it is possible to select a output depending on the logged in user. So when one user/token calls GET http://my-url/contacts
it returns only the contacts for that specific user?
Until now I've made a with:
Contacts.methods(['get']).after('get', discardContactsForOtherUsers)
But this is pretty heavy, is there a cleaner way?
Responding from mobile so excuse brevity. That method will needlessly fetch a lot more data than needed and will break with pagination and such.
The best way to do this would be with a before route. I assume you already have access to the user.
In the before filter, you can inspect the user and then modify req.body or req.data with the foreign key to the logged in user. Ie if you contact model has a field user_id that points to your user model,
req.data.user_id = req.user.id
Or whatnot and then call next().
I have a similar question. I'd like to use something like mongoose-diff-history to keep a log of who made changes to the DB. Following the above example, I can put the user info into req.body, but it's not clear where to use that info on the mongoose side. If user_id isn't a field in the schema, it gets dropped somewhere before the mongoose pre hook.
Of course, I could add a dummy field to the schema to make it available in the mongoose pre hook, but that feels clumsy. I also realize I could do my own DB calls in the before hook, but I'd rather leverage existing code if possible.
Any guidance would be greatly appreciated; thanks!