【问题标题】:CompoundJS: Create model from external REST APICompoundJS:从外部 REST API 创建模型
【发布时间】:2013-09-03 15:56:52
【问题描述】:

我有一个外部 RESTful 端点,我正试图在我的 CompoundJS 应用程序中构建一个模型。我对几件事有点困惑:

  1. 如何使用外部 RESTful API 构建模型(大多数模型似乎都以数据库为中心)?
  2. 访问此 RESTful API 的最佳方式是什么?

现在,我正在这样做:

var options = {
  host: 'api.local',
  port: 80,
  path: '/users',
  method: 'GET',
  headers: {
    'Content-Type': 'application/json'
  }
};

var http = require('http');
http.get(options, function(res) {
  var output = "";
  res.on('data', function(chunk) {
    output += chunk;
  });

  res.on('end', function() {
    var obj = JSON.parse(output);
    send({code: 200, data: obj});
  });
});

obj 实际上返回了我所有的用户数据(但在 JSON 中)。返回的 JSON 如下所示:

{
  time: integer,
  count: integer,
  data: [{
    userid: string,
    name: string,
    email: string
  }, {
    userid: string,
    ...
  }]
}

JSON 非常棒,但我很想将它加载到模型中,所以我想我会有一个包含 time(整数类型)、count(整数类型)的外部模型, 和 data (类型为数组)。然后我有一个内部模型(我们称之为User),它包含userid(字符串类型)、name(字符串类型)和email(字符串类型)。然后我必须将data 与拥有许多User 模型相关联。我希望有类似Ext JS does it 的东西。

那么,如何根据这个 RESTful 端点的返回来构建模型,以及从端点获取这些数据的最佳方式是什么?我当前的代码是否高于获取数据的最佳路径,或者我可以使用我在Schema.js 中创建的模型设置更简洁的方法?理想情况下,我可以在 Schema.js 中创建一个模型,将其与 RESTful API 挂钩,然后执行正常的 GET/POST 操作。

任何帮助将不胜感激!

【问题讨论】:

    标签: node.js api rest compoundjs railway.js


    【解决方案1】:

    我想出的当前工作解决方案......似乎工作,但它看起来有点hacky。如果您看到 TODO 评论,那就是我希望能够做到的事情......我只是想知道此时是否有可能。这让我可以控制用户模型显示/隐藏的内容,所以我更开心了。

    Schema.js

    var User = describe('User', function() {
      property('userid', String);
      property('name', String);
      property('email', String);
      set('restPath', pathTo.users);
    });
    
    var Hash = describe('Hash', function () {
        property('time', Number);
        property('count', Number);
        property('data', new Array());
        set('restPath', pathTo.hashes);
    });
    

    hashes_controller.js

    var options = {
      host: 'api.local',
      port: 80,
      path: '/users',
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    };
    
    var http = require('http');
    http.get(options, function(res) {
      var output = "";
      res.on('data', function(chunk) {
        output += chunk;
      });
    
      res.on('end', function() {
        var obj = JSON.parse(output);
        var data = {};
        data.msec = obj.msec;
        data.count = obj.count;
        data.users = [];
        // TODO: Ideally, this is what I would like to do
        // var hash = new Hash(obj);
        for (var i = 0; i < obj.data.length; i++) {
          var user = new User(obj.data[i]);
          data.users.push(user);
        }
        send({code: 200, data: data});
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2013-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      • 2018-04-27
      相关资源
      最近更新 更多