riotapi-js
Version:
Riot API written in NodeJS
70 lines (54 loc) • 2.13 kB
JavaScript
;
var util = require("./util"),
http = require("http"),
https = require("https"),
Q = require("q");
var PROTOCOL_REGEXP = /^([a-zA-Z]+):\/\//;
var Endpoint = function(url, opts) {
var match = url.match(PROTOCOL_REGEXP),
protocol = ((match && match[1]).toLowerCase() || "http");
if (protocol !== "https" && protocol !== "http")
throw new URIError("Unsupported URI protocol");
this.url = url;
this.multiple = opts["multiple"] === true;
this.protocol = protocol;
};
Endpoint.prototype.query = function(tokens) {
var url = util.format(this.url, tokens),
client = this.protocol === "https" ? https : http,
promise = query(client, url);
if (this.multiple || !tokens["id"])
return promise;
var id = tokens["id"];
return promise.then(function(object) {
return object && object[id];
});
};
function query(client, url) {
var deferred = Q.defer(),
state = { status: null, object: null, error: null };
client.get(url, function(response) {
var data = "",
contentType = response.headers["content-type"];
response.on("data", function(s) {
data += s;
});
response.on("end", function() {
state.status = response.statusCode;
if (contentType && contentType.indexOf("application/json") >= 0) {
// If it's a JSON response we can try and parse it
try { state.object = JSON.parse(data); }
catch(err) { /* malformed JSON from the server, ignore it */ }
}
// Resolve only 404/200 as they are 'expected' status codes (i.e. not actual "errors")
state.status === 200 || state.status === 404
? deferred.resolve(state.object)
: deferred.reject(state);
});
}).on("error", function(e) {
state.error = e;
deferred.reject(state);
});
return deferred.promise;
}
module.exports = Endpoint;