Created
April 14, 2014 14:56
-
-
Save DamienBell/10655539 to your computer and use it in GitHub Desktop.
App.get //basic ajax request.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
App= { | |
/* | |
config= { | |
options:{ | |
host: 'ichart.yahoo.com', | |
path: '/table.csv?s=GOOG&a=01&b=1&c=2013' | |
}, | |
success: function(json){}, | |
error: function(error){} | |
} | |
*/ | |
//general api to get this and that | |
get: function(config){ | |
var _callback = function(response) { | |
var str = ''; | |
//another chunk of data has been recieved, so append it to `str` | |
response.on('data', function (chunk) { | |
str += chunk; | |
}); | |
response.on('error', function(error){ | |
if(config.error && typeof(config.error) == "function"){ | |
config.error(error); | |
} | |
}); | |
//the whole response has been recieved | |
response.on('end', function () { | |
if(config.success && typeof(config.success) == 'function'){ | |
config.success(str); | |
} | |
}); | |
} | |
http.request(config.options, _callback).end(); | |
}, | |
apiResponse: function(res,data,format) { | |
if (!format || format=='json') { | |
res.json({ | |
status:'ok', | |
response: data | |
}); | |
} else if (format=='jsonp') { | |
res.jsonp({ | |
status:'ok', | |
response: data | |
}); | |
} | |
}, | |
error: function(res,message) { | |
console.log('!!!! ERROR !!!! ' + message); | |
// res.send(500,message); | |
var obj ={}; | |
if (typeof(message)=='string') { | |
obj = {message: message}; | |
} else { | |
obj = message; | |
} | |
res.json( | |
{ | |
status:'error', | |
error: obj | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment