Automatically add session information for a model in Sails.js

So I need to create associations in Sails.js. Which is pretty easy to do with something like these models using collection attributes:

Article.js

...
  attributes: {
        creator: {
            model: 'user'
        }
  ...

      

user.js

...
    attributes: {
        articles: {
            collection: 'article',
            via: 'creator'
        },
    }
...

      

Then when I create a new article, I can bind the userId in my DB to the "creator" attribute / argument and get / display automatically via the ORM.

However, I would like to know how I can make this association automatically through the session used by the sails. So I don't have to search by user id or (gasp) to store user id and pass it back and forth over the wires.

My little MVC knowledge dictates that this logic belongs to the controller, but by default I can CRUD for my articles without anything inside ArticleController.js

+3


source to share


1 answer


If you have a user who already has a session, they should pass a token with their request. It's as simple as pulling the userID from the token (if it's already in the token).



You can access the token as a property of the request object. In your case, it will most likely be as simple as setting userId = req.token.id;

inside your create method and assigning whatever field you want.

+2


source







All Articles