Skip to content

Commit

Permalink
Handle invalid token for subscribe request
Browse files Browse the repository at this point in the history
Fixes #207
  • Loading branch information
brycekahle committed Feb 9, 2016
1 parent 59ce27b commit 34b53cc
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 18 deletions.
20 changes: 11 additions & 9 deletions commands/SubscribeCommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,21 +26,21 @@ License along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
'use strict';

var settings = require('../settings.js');
var when = require('when');
var extend = require('xtend');
var util = require('util');

var BaseCommand = require('./BaseCommand.js');
var ApiClient = require('../lib/ApiClient.js');


var SubscribeCommand = function (cli, options) {
function SubscribeCommand(cli, options) {
SubscribeCommand.super_.call(this, cli, options);
this.options = extend({}, this.options, options);

this.init();
};
util.inherits(SubscribeCommand, BaseCommand);

SubscribeCommand.prototype = extend(BaseCommand.prototype, {
options: null,
name: 'subscribe',
Expand Down Expand Up @@ -82,10 +82,10 @@ SubscribeCommand.prototype = extend(BaseCommand.prototype, {
}

var chunks = [];
var appendToQueue = function(arr) {
for (var i=0;i<arr.length;i++) {
function appendToQueue(arr) {
for (var i = 0; i < arr.length; i++) {
var line = (arr[i] || '').trim();
if (line === '') {
if (!line) {
continue;
}
chunks.push(line);
Expand All @@ -112,11 +112,13 @@ SubscribeCommand.prototype = extend(BaseCommand.prototype, {
console.log(JSON.stringify(obj));
};

var onData = function(event) {
return api.getEventStream(eventName, deviceId, function(event) {
var chunk = event.toString();
appendToQueue(chunk.split('\n'));
};
api.getEventStream(eventName, deviceId, onData);
}).catch(function(err) {
console.error('Error', err);
return when.reject(err);
});
}
});

Expand Down
26 changes: 17 additions & 9 deletions lib/ApiClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,7 @@ ApiClient.prototype = {
},

getEventStream: function (eventName, deviceId, onDataHandler) {
var self = this;
var url;
if (!deviceId) {
url = '/v1/events';
Expand All @@ -693,16 +694,23 @@ ApiClient.prototype = {
}

console.log('Listening to: ' + url);
var requestObj = this.request({
uri: url + '?access_token=' + this._access_token,
method: 'GET'
return when.promise(function(resolve, reject) {
self.request
.get({
uri: url,
qs: {
access_token: self._access_token
}
})
.on('response', function(response) {
if (self.isUnauthorized(response)) {
reject('Invalid access token');
}
})
.on('error', reject)
.on('close', resolve)
.on('data', onDataHandler);
});

if (onDataHandler) {
requestObj.on('data', onDataHandler);
}

return requestObj;
},

publishEvent: function (eventName, data, setPrivate) {
Expand Down

0 comments on commit 34b53cc

Please sign in to comment.