3

I am a newbie to NodeJS and Sails.js.

I want create a REST API that allows me to expand a resource based on query parameter. For eg

HTTP GET /snippets


{
"count": 1, 
"next": null, 
"previous": null, 
"results": [
    {
        "url": "http://localhost:8000/snippets/1/", 
        "highlight": "htep://localhost:8000/snippets/1/highlight/", 
        "title": "test", 
        "code": "def test():\r\n     pass", 
        "linenos": false, 
        "language": "Clipper", 
        "style": "autumn", 
        "owner": "http://localhost:8000/users/2/", 
        "extra": "http://localhost:8000/snippetextras/1/"
    }
]}


HTTP GET /snippets?expand=owner
{
"count": 1, 
"next": null, 
"previous": null, 
"results": [
    {
        "url": "http://localhost:8000/snippets/1/", 
        "highlight": "http://localhost:8000/snippets/1/highlight/", 
        "title": "test", 
        "code": "def test():\r\n     pass", 
        "linenos": false, 
        "language": "Clipper", 
        "style": "autumn", 
        "owner": {
            "url": "http://localhost:8000/users/2/", 
            "username": "test", 
            "email": "test@test.com"
        }, 
        "extra": "http://localhost:8000/snippetextras/1/"
    }
]}

Wondering how can I do that in Sails.js or NodeJS?

Gaurav Verma
  • 645
  • 1
  • 6
  • 15

1 Answers1

3

You should use assocations.

Here is how you would create a one-to-many association between your User model and your Snippet model:

// User.js
module.exports = {
  // ...
  attributes: {
    // ...
    snippets: {
      collection: 'Snippet',
      via: 'owner'
    }
  }
};

// Snippet.js
module.exports = {
  // ...
  attributes: {
    // ...
    owner: {
      model: 'User'
    }
  }
};

Then you can hit /snippets if you want a list of snippets, and hit /snippets?populate=[owner] if you need details about the owners of the snippets.

Yann Bertrand
  • 3,084
  • 1
  • 22
  • 38
  • Thanks Yand, that helped. I actually wanted it to go one level deeper. I found this issue with waterline which only allows for one level of expansion https://github.com/balderdashy/waterline/issues/308 – Gaurav Verma Aug 04 '15 at 11:15
  • And there is a pull request that will hopefully make it to the next version. https://github.com/balderdashy/waterline/pull/1052 – Gaurav Verma Aug 04 '15 at 11:16
  • To my knowledge, this is not planned for next release (v0.12). But you can create your own controller's action and route if you really want it. – Yann Bertrand Aug 04 '15 at 11:23
  • Ok, I will give that a shot then. Any thing you can point me to , to help with that? – Gaurav Verma Aug 06 '15 at 00:54
  • 1
    Check out [this question](http://stackoverflow.com/questions/23446484/sails-js-populate-nested-associations)! – Yann Bertrand Aug 06 '15 at 07:23