Skip to content

Instantly share code, notes, and snippets.

@michaelkuty
Last active January 6, 2016 17:14
Show Gist options
  • Save michaelkuty/825bdb8d8d547055cb99 to your computer and use it in GitHub Desktop.
Save michaelkuty/825bdb8d8d547055cb99 to your computer and use it in GitHub Desktop.
Simple HTTP client in JS for NodeJS
var request = require('request');
var rp = require('request-promise');
export default function Model(model) {
/* Encapsulate Django Rest Frameowork actions
var page = new Model('web.page');
page.list(function (pages) {
console.log(pages);
});
page.create({title: "My Page"}, function (page) {
console.log(page);
});
*/
this.model = model;
this.list = function(callback) {
return this.request(this.endpoint(), {}, 'GET', callback);
};
this.get = function(id, callback) {
return this.request(
this.endpoint() + id + '/', {}, 'GET', callback);
};
this.update = function(id, data, callback) {
return this.request(
this.endpoint() + id + '/', data, 'PUT', callback);
};
this.delete = function(id, callback) {
return this.request(
this.endpoint() + id + '/', {}, 'DELETE', callback);
};
this.create = function(data, callback) {
return this.request(this.endpoint(), data, 'POST', callback);
};
this.endpoint = function() {
return '/api/models/' + this.model + '/';
};
this.request = function (url, data, method, callback) {
/* make reqeust */
console.log(method, 'http://10.10.10.122' + url, data);
var options = {
method: method,
url: 'http://10.10.10.122' + url,
json: true,
formData: data};
rp(options)
.then(function (parsedBody) {
// POST succeeded...
console.log(parsedBody);
return parsedBody;
})
.catch(function (err) {
// POST failed...
console.log(err);
return err;
});
//request(options,
// function (e, r, body) {
// console.log('Response: ', body);
// if (body.results !== 'undefined') {
// callback(body.results);
// } else {
// callback(body);
// }
//});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment