【问题标题】:How do I expand nested relationships in REST API using Sails.js如何使用 Sails.js 在 REST API 中扩展嵌套关系
【发布时间】:2015-10-17 09:27:58
【问题描述】:

我是 NodeJS 和 Sails.js 的新手。

我想创建一个允许我根据查询参数扩展资源的 REST API。例如

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/"
    }
]}

想知道如何在 Sails.js 或 NodeJS 中做到这一点?

【问题讨论】:

    标签: javascript node.js rest sails.js


    【解决方案1】:

    你应该使用assocations

    以下是在 User 模型和 Snippet 模型之间创建一对多关联的方法:

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

    然后,如果您需要 sn-ps 列表,可以点击/snippets,如果您需要有关 sn-ps 所有者的详细信息,请点击 /snippets?populate=[owner]

    【讨论】:

    • 谢谢扬德,这有帮助。我实际上希望它更深一层。我发现这个水线问题只允许一级扩展github.com/balderdashy/waterline/issues/308
    • 还有一个拉取请求,希望它能够进入下一个版本。 github.com/balderdashy/waterline/pull/1052
    • 据我所知,下一个版本 (v0.12) 没有计划。但是如果你真的想要的话,你可以创建自己的控制器的动作和路由。
    • 好的,那我试试看。有什么可以指点我的吗?
    • 查看this question
    猜你喜欢
    • 2013-05-19
    • 1970-01-01
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    • 2014-10-24
    • 2014-06-20
    相关资源
    最近更新 更多