Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not throw from async callbacks #5

Merged
merged 1 commit into from
Dec 16, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 31 additions & 23 deletions lib/Client.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@ var Q = require('q'),


/**
Client
@constructor
@param {string} key - Login access key, as seen in the creator developer console
@param {string} secret - Login access secret token, as seen in the creator developer console
@param {object} options (optional) - optional config for the REST client
- @member {string} host - host for the Creator Device Server REST API
**/
Client
@constructor
@param {string} key - Login access key, as seen in the creator developer console
@param {string} secret - Login access secret token, as seen in the creator developer console
@param {object} options (optional) - optional config for the REST client
- @member {string} host - host for the Creator Device Server REST API
**/
function Client(key, secret, host, timeout) {

/* Required client config */
Expand All @@ -38,7 +38,7 @@ function Client(key, secret, host, timeout) {
this.timeout = timeout || 31000; // request timeout in milliseconds


Authenticator.authenticate(key, secret).then(function(t){
Authenticator.authenticate(key, secret).then(function (t) {
this.authorization = t;
});

Expand All @@ -54,47 +54,55 @@ Client.prototype.constructURL = function (extension) {

/**
Make an authenticated request against the Creator Device Server.
*/
*/
Client.prototype.request = function (options, callback) {
var client = this,
deferred = Q.defer();

/* Set Options fields */
options.headers = {'Accept': 'application/json', 'Accept-Charset': 'utf-8', 'User-Agent': 'creator-node/' + moduleinfo.version, };
if(!options.timeout) options.timeout = client.timeout; // default timeout
if(options.follow === undefined) options.follow = true; // following by default
if(!options.method) options.method = "GET";
if(!options.nocache) options.nocache = false;
options.headers = {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'creator-node/' + moduleinfo.version,
};
if (!options.timeout) options.timeout = client.timeout; // default timeout
if (options.follow === undefined) options.follow = true; // following by default
if (!options.method) options.method = "GET";
if (!options.nocache) options.nocache = false;

var rel = options.relativeEntryPoint;
if(rel)
if(rel.indexOf('http') > -1 || rel.indexOf('https') > -1 || rel.indexOf('www') > -1)
if (rel)
if (rel.indexOf('http') > -1 || rel.indexOf('https') > -1 || rel.indexOf('www') > -1)
throw config.ONLY_RELATIVE_ERROR;

switch (options.method) {
case "PUT":
case "POST":
if(typeof options.data === 'object') {
if (typeof options.data === 'object') {
options.body = JSON.stringify(options.data);
options.headers["content-type"] = "application/json";
}
break;
}

if(options.follow) {
if (options.follow) {
if (!options.steps) throw config.STEPS_ERROR;
else {
// Authenticate first
Authenticator.authenticate(this.authKey, this.authSecret).then(function(t){
Authenticator.authenticate(this.authKey, this.authSecret).then(function (t) {
this.authorization = t;

// Then navigate
Navigator.getURL(options.steps, this.authorization, options.relativeEntryPoint, options.nocache).then(function(url){
options.headers.Authorization = this.authorization.token; options.url = url;
Navigator.getURL(options.steps, this.authorization, options.relativeEntryPoint, options.nocache).then(function (url) {
options.headers.Authorization = this.authorization.token;
options.url = url;

// And finally send out the final request
request(options, function (err, response, body) {
if(err) throw 'There has been an error: ' + err;
if (err) {
deferred.reject(err);
return;
}
deferred.resolve(new Client.prototype.response(response.statusCode, body));
});
});
Expand All @@ -113,7 +121,7 @@ Client.prototype.request = function (options, callback) {
* TODO
*/

Client.prototype.response = function(statusCode, body) {
Client.prototype.response = function (statusCode, body) {
this.statusCode = statusCode;
this.body = body ? JSON.parse(body) : null;
};
Expand Down
18 changes: 9 additions & 9 deletions lib/resources/authenticator.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
@module resources/Authenticator
This module gets the Client authenticated against the Creator Device Server
This module gets the Client authenticated against the Creator Device Server
using the access key and secret pair - and lets the client do authenticated calls
by appending an access token field into the Client (super_) class
*/
Expand All @@ -17,33 +17,33 @@ var authorization = {
/* @method authenticate
* @param {key, secret} the key and secret access keys
* @return {Promise} when resolved, returns valid session data or rejects if authentication failed
* @public
* @public
*/
function authenticate(key, secret) {
return new p(function (resolve, reject) {
if(key && secret) {
if(authorization.token === null) {
request.post({
url: config.defaultHost + config.defaultAuthEndpoint,
request.post({
url: config.defaultHost + config.defaultAuthEndpoint,
headers: {
"Content-Type": 'application/x-www-form-urlencoded'
},
form: {
username: key,
password: secret,
grant_type: "password"
}},
}},
function(err,httpResponse,body){
if(body && body !== undefined){
body = JSON.parse(body);
authorization.token_type = body.token_type;
authorization.access_token = body.access_token;
authorization.token = body.token_type + ' ' + body.access_token;

resolve(authorization);
}
}
else {
throw 'There has been an error during the authentication process';
reject(new Error('There has been an error during the authentication process'));
}
});
}
Expand All @@ -54,4 +54,4 @@ function authenticate(key, secret) {
}


module.exports = { authenticate: authenticate, authorization: authorization }; /* Object short notation is only available in ES6 :( */
module.exports = { authenticate: authenticate, authorization: authorization }; /* Object short notation is only available in ES6 :( */
10 changes: 5 additions & 5 deletions lib/resources/navigator.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ function navigate(url, _steps, authorization, nocache, resolve, reject) {
try {
JSON.parse(data);
} catch (error) {
throw('Web service has returned an invalid JSON.');
reject(new Error('Web service has returned an invalid JSON.'));
}

// Store in the cache
Expand Down Expand Up @@ -89,13 +89,13 @@ function navigateSteps(data, _steps, authorization, nocache, resolve, reject){
}
else {
if(index + 1 == data.Items.length){
throw('You have objects available in this resource group but the filter {' + keyToLook + ": " + _steps[0][keyToLook] + '} did not return a valid result. Please note data types matter.');
reject(new Error('You have objects available in this resource group but the filter {' + keyToLook + ": " + _steps[0][keyToLook] + '} did not return a valid result. Please note data types matter.'));
}
}
});
}
else {
throw('{' + keyToLook + ': '+ _steps[0][keyToLook] +'} could not be found in the payload. You don\'t have any objects in this resource group.');
reject(new Error('{' + keyToLook + ': '+ _steps[0][keyToLook] +'} could not be found in the payload. You don\'t have any objects in this resource group.'));
}
}
else if(data.Links){
Expand All @@ -113,11 +113,11 @@ function navigateSteps(data, _steps, authorization, nocache, resolve, reject){
}
}
else if(index + 1 == Links.length){
throw('The Link you specified could not be found in the payload');
reject(new Error('The Link you specified could not be found in the payload'));
}
});
}
else {
throw('The link you specified could not be found in the payload. Please check host, relativeEntryPoint and steps options.');
reject(new Error('The link you specified could not be found in the payload. Please check host, relativeEntryPoint and steps options.'));
}
}