Skip to content

Instantly share code, notes, and snippets.

@justin-nodeboy
Last active September 9, 2015 07:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justin-nodeboy/76671f9cc607b7fec917 to your computer and use it in GitHub Desktop.
Save justin-nodeboy/76671f9cc607b7fec917 to your computer and use it in GitHub Desktop.
A simple API function for calling an endpoint in Titanium, see demo.js for usage
/**
Use this function to make calls to a JSON REST API see demo.js for useage
@param options
@param end (Callback)
**/
exports.api = function(options, end) {
//This function makes calls to an Endpoint and then sends the data back via callback to the function that requested it.
//Alloy.CFG.conn_url is set in your config.json file and can be accessed depending on which environment you are using.
var method = options.method,
conn_url = Alloy.CFG.conn_url,
params = {},
verb = options.verb,
xhr = Ti.Network.createHTTPClient(),
error_message;
if (options.params){
params = options.params;
}
xhr.onload = function(e) {
var result;
//JSON object is parsed and sent back ready to use
result = JSON.parse(this.responseText);
end(null, result);
};
xhr.onsendstream = function(e) {
//You can listen to this event to then create a Titanium Progress Bar
Ti.App.fireEvent('progress', {
progress: e.progress
});
};
xhr.onerror = function(e) {
//Error handling
var result;
result = JSON.parse(this.responseText);
error_message = new Error(result.error);
end(error_message.message);
};
xhr.open(verb, conn_url + method;);
xhr.send(params);
};
var api = require('api');
function do_post(){
var options = {
verb: "POST",
method: "/post/something",
params:{
param1:"stuff",
param2:"more stuff"
}
};
api.api(options, function (err, result){
if (err){
//Do error handling
} else {
//result is the parsed response from the server
}
});
}
function do_get(){
var options = {
verb: "GET",
method: "/get/something"
};
api.api(options, function (err, result){
if (err){
//Do error handling
} else {
//result is the parsed response from the server
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment