sparkmls-api
Version:
Spark MLS Api client
138 lines (113 loc) • 4.76 kB
JavaScript
/**
* Created by martins on 1/31/16.
*/
var request = require('request');
var ref = require('./apiRef.json');
var md5 = require('md5');
var sparkclient = SparkApiClient.prototype;
function SparkApiClient(strApiKey, strApiSecret){
this.creds = {
apiKey : strApiKey,
apiSecret : strApiSecret
};
this.authmode = "none";
this.authRequest = false;
this.get = {
listings : new (require('./model/listings.js'))(this),
my : new (require('./model/my.js'))(this)
};
}
sparkclient.setAuthMode = function(strAuthMode){
var allowedAuthModes = [ "sparkapi", "oauth2" ];
if(allowedAuthModes.indexOf(strAuthMode) != -1 ){
this.authmode = strAuthMode;
}
};
sparkclient.generateApiSignature = function (uri, args){
var authSignature = "{SECRET}ApiKey{APIKEY}";
var pathSignature = "ServicePath{SERVPATH}AuthToken{AUTHTOKEN}";
var paramFormat = "{pname}{pval}";
var actionSignature = authSignature;
actionSignature = actionSignature.replace(/\{SECRET}/g, this.creds.apiSecret)
.replace(/\{APIKEY}/g, this.creds.apiKey);
if(uri.indexOf('session') == -1) {
actionSignature += pathSignature;
actionSignature = actionSignature.replace(/\{SERVPATH}/g, uri.replace(ref.spark.api.rootPath, '')).replace(/\{AUTHTOKEN}/g, this.creds.authToken.AuthToken);
if(args != undefined){
var argKeys = Object.keys(args);
if(argKeys.length > 0){
// append the parameters via format ^ to the hash string
for(var ix = 0; ix < argKeys.length; ix++)
actionSignature += paramFormat.replace(/\{pname}/g, argKeys[ix]).replace(/\{pval}/g, args[argKeys[ix]]);
}
}
}
// get/return the hash from the actionSignature
return md5(actionSignature);
};
sparkclient.request = function (requestType, uri, callback, params, authRequest, isRetry) {
var self = this;
isRetry = isRetry != undefined ? isRetry : false;
if(this.creds.authToken === undefined && !this.authRequest || isRetry)
this.authenticate(_processRequest);
else {
_processRequest();
}
function _processRequest() {
var rUri = uri;
var validParams = params != undefined && typeof params == 'object';
var apiSig = self.generateApiSignature(rUri, validParams ? params : undefined);
var paramsString = "";
if(requestType != 'POST' && validParams){
var pKeys = Object.keys(params);
for(var ix = 0; ix < pKeys.length; ix++){
paramsString += '&' + pKeys[ix] + '=' + params[pKeys[ix]];
}
}
var uriString = rUri + (self.authRequest ? "?ApiKey=" + self.creds.apiKey : "?AuthToken=" + self.creds.authToken.AuthToken) + "&ApiSig=" + apiSig + paramsString;
// run the request
request({
method: requestType,
uri: uriString,
headers: { "X-SparkApi-User-Agent": "sparkmls-api-client" },
postData: requestType == 'POST' ? params : undefined
}, function (e, res, body) {
var msg;
try {
msg = JSON.parse(body);
} catch (e) { }
if (!e && res.statusCode == 200) {
if (msg.D.Success) {
var retObject = {success: {status: true}, data: msg.D.Results};
callback(retObject);
} else {
callback({success: {status: false, reason: "Error Code: " + res.statusCode}});
}
} else {
if(res.statusCode == 401 && msg.D.Code == 1020) // token has expired
self.authenticate(_processRequest, true);
else
callback({success: {status: false, reason: "Could not connect to API: " + msg == undefined ? body : ""}});
}
});
}
};
/// Authenticates with the SparkMLS API platform and internalizes
/// a reference to the API key.
sparkclient.authenticate = function (callback, forceReauth) {
var self = this;
forceReauth = forceReauth != undefined ? forceReauth : false;
if(this.creds.authToken == undefined || this.creds.expires < new Date() || forceReauth){
self.authRequest = true;
this.request('POST', ref.spark.api.rootPath + ref.spark.api.v1.session.uri, function(res){
var credData = res.data[0];
self.creds.authToken = credData;
self.creds.expires = new Date(credData.Expires);
self.authRequest = false;
callback(credData);
}, {}, true);
} else {
callback(this.creds.authToken);
}
};
module.exports = SparkApiClient;