node.js - CompoundJS: Create model from external REST API -
i've got external restful endpoint i'm trying build model off of in compoundjs app. i'm bit confused couple of things:
- how build model off of external restful api (most models seem database focused)?
- what's best way access restful api?
right now, i'm doing this:
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
return of user data (but in json). json returned looks this:
{ time: integer, count: integer, data: [{ userid: string, name: string, email: string }, { userid: string, ... }] }
json's great , all, i'd love load model, i'm thinking have outer model contains time
(with type integer), count
(with type integer), , data
(with type array). have inner model (let's call user
) contains userid
(with type string), name
(with type string), , email
(with type string). have associate data
having many user
models. i'm hoping along lines of how ext js it.
so how build model based on restful endpoint's return, , what's best way of getting data endpoint? current code above best route grabbing data, or can set cleaner approach using model create in schema.js
? ideally, i'd able create model in schema.js
, hook restful api, , normal get/post operations.
any appreciated!
current working solution came with... seems work, looks bit hacky. if see todo comment, i'd love able do... i'm wondering if it's possible @ point. allows me control user model shows/hides, i'm bit happier.
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, // var hash = new hash(obj); (var = 0; < obj.data.length; i++) { var user = new user(obj.data[i]); data.users.push(user); } send({code: 200, data: data}); }); });
Comments
Post a Comment