-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
437 lines (381 loc) · 18.9 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
/*!
* node-misfit
* Copyright(c) 2015 Armin Tamzarian <tamzarian1989@gmail.com>
* MIT Licensed
*/
'use strict';
var moment = require('moment');
var querystring = require('querystring');
var request = require('superagent');
var util = require('util');
function InvalidDateError(message) {
this.name = 'InvalidDateError';
this.message = message
}
InvalidDateError.prototype = Error.prototype;
function InvalidDateRangeError(message) {
this.name = 'InvalidDateRangeError';
this.message = message
}
InvalidDateRangeError.prototype = Error.prototype;
function InvalidParameterError(message) {
this.name = 'InvalidParameterError';
this.message = message
}
InvalidParameterError.prototype = Error.prototype;
function MisfitError(error) {
var errorData = error.text ? JSON.parse(error.text) : {type: 'unknown', error_description: 'Unexpected error'};
this.name = 'MisfitError';
this.status = error.status;
this.type = errorData.error || 'api';
this.message = errorData.error_description || errorData.message;
};
MisfitError.prototype = Error.prototype;
function RequiredParameterError(parameters) {
this.name = 'RequiredParameterError';
this.message = util.format('Required parameter%s missing: %s', parameters.length > 1 ? '(s)' : '', parameters.join(', '));
}
RequiredParameterError.prototype = Error.prototype;
var NodeMisfit = (function () {
var MISFIT_CLOUD_BASE_URL = 'https://api.misfitwearables.com';
var MISFIT_DEFAULT_USERID = 'me';
var PATH_AUTH_AUTHORIZE = '/auth/dialog/authorize';
var PATH_AUTH_EXCHANGE_TOKEN = '/auth/tokens/exchange';
var PATH_RESOURCE_PROFILE = '/move/resource/v1/user/%s/profile';
var PATH_RESOURCE_DEVICE = '/move/resource/v1/user/%s/device';
var PATH_RESOURCE_GOALS = '/move/resource/v1/user/%s/activity/goals';
var PATH_RESOURCE_SUMMARY = '/move/resource/v1/user/%s/activity/summary';
var PATH_RESOURCE_SESSIONS = '/move/resource/v1/user/%s/activity/sessions';
var PATH_RESOURCE_SLEEPS = '/move/resource/v1/user/%s/activity/sleeps';
/**
* node-misfit constructor
*
* @param {Object} options - Configuration options for the node-misfit object
* {String} clientId- Client ID for the Misfit API application
* {String} clientSecret - Client secret for the Misfit API application
* {String} redirectUri - URL to redirect the browser to after authorization requests
* {String} scope - Data parameters to which requests should be limited
* @param {String} apiUrl - Optional URL to override the Misfit Cloud API base URL for testing or customization purposes
* @public
*/
var nodeMisfit = function (options, apiUrl) {
options = options || {};
var setup = {
clientId: options.clientId || '',
clientSecret: options.clientSecret || '',
redirectUri: options.redirectUri || '',
scope: options.scope || 'public,birthday,email,tracking,session,sleeps',
apiUrl: apiUrl || MISFIT_CLOUD_BASE_URL
};
/**
* Checks to see if the supplied object is a function
*
* @param {Object} obj - Object to test if it is a function
*
* @private
*/
var isFunction = function (obj) {
return typeof obj == 'function' || false;
};
/**
* Validate that required parameters have been provided to the function call.
*
* @param {Array<String>} parameters - Supplied parameter values
*
* @private
*/
var checkRequired = function(parameters) {
var missing = [];
var parameters = Array.prototype.slice.call(parameters);
var req = Array.prototype.slice.call(arguments, 1);
for(var i = 0; i < req.length; i++) {
if(!parameters[i]) {
missing.push(req[i]);
}
}
if(missing.length > 0) {
throw new RequiredParameterError(missing);
}
return true;
};
/**
* Validate supplied date strings for conformance with Misfit Cloud API requirements.
*
* @param {String} startDate - Beginning range for the resource query
* @param {String} endDate - End range for the resource query
*
* @private
*/
var validateDates = function (startDate, endDate) {
var startMoment = moment(startDate, 'YYYY-MM-DD');
var endMoment = moment(endDate, 'YYYY-MM-DD');
if(!startMoment.isValid()) {
throw new InvalidDateError(util.format('Invalid startDate %s', startDate));
}
if(!endMoment.isValid()) {
throw new InvalidDateError(util.format('Invalid endDate %s', endDate));
}
if(endMoment.isBefore(startMoment)) {
throw new InvalidDateRangeError(util.format('endDate may not precede startDate'));
}
if(startMoment.diff(endMoment, 'days') > 30) {
throw new InvalidDateRangeError(util.format('Date range is greater than 30 days'));
}
}
/**
* Get a Misfit resource matching the supplied information
*
* @param {String} accessToken - The user's access token to authenticate the request
* @param {String} requestPath - Path for the request
* @param {Object} queryParameters - Query parameters to include with the request
* @param {String} userId - Optional id for the user
* @param {String} objectId - Optional object of the resource
* @param {Function(err, resource)} callback - Optional callback to execute on completion of the request
*
* @private
*/
var getResource = function (accessToken, requestPath, queryParameters, userId, objectId, callback) {
userId = userId || MISFIT_DEFAULT_USERID;
request
.get(objectId ? util.format(requestPath + '/%s', userId, objectId) : util.format(requestPath, userId))
.query(queryParameters)
.set('Authorization', util.format('Bearer %s', accessToken))
.end(function (err, response) {
if(!isFunction(callback)) { return; }
if (response.error) {
return callback(new MisfitError(response.error));
}
callback(null, response.body);
});
}
/**
* Get the authorization URL for the configured node-misfit object
*
* @param {String} type - Type of response to the request of type 'code' or 'token'. If not specified 'code'.
*
* @see {@link https://build.misfit.com/docs/references#APIReferences-Authorize3rd-partyapptoaccessShinedata|Misfit - Authorize a 3rd-party app}
* @public
*/
this.getAuthorizeUrl = function (type) {
var responseType = type || 'code';
if(responseType !== 'code' && responseType !== 'token') {
throw new InvalidParameterError('type must be of value "code" or "token"')
}
return util.format('%s%s?%s', setup.apiUrl, PATH_AUTH_AUTHORIZE, querystring.stringify({
response_type: responseType,
client_id: setup.clientId,
redirect_uri: setup.redirectUri,
scope: setup.scope
}));
};
/**
* Exchange a Misfit API authorization code for an access token
*
* @param {String} authorizationCode - The authorization code to exchange for an access token
* @param {Function(err, token)} callback - Optional callback to execute on completion of the request
*
* @throws {RequiredParameterError} Argument authorizationCode required
*
* @see {@link https://build.misfit.com/docs/references#APIReferences-Getaccesstokenfromauthorizedcode|Misfit - Get access token from authorized code}
* @public
*/
this.getAccessToken = function (authorizationCode, callback) {
checkRequired(arguments, 'authorizationCode');
request
.post(util.format('%s%s', setup.apiUrl, PATH_AUTH_EXCHANGE_TOKEN))
.send({
grant_type: 'authorization_code',
code: authorizationCode,
redirect_uri: setup.redirectUri,
client_id: setup.clientId,
client_secret: setup.clientSecret
})
.end(function (err, response) {
if(!isFunction(callback)) { return; }
if(response.error) {
return callback(new MisfitError(response.error));
}
callback(null, response.body.access_token);
});
};
/**
* Get the profile for the specified user.
*
* @param {String} accessToken - The user's access token to authenticate the request
* @param {String} options - Optional set of options to configure the request.
* {String} userId - User id of the profile resource owner. If not specified assumed to be 'me'
* {String} objectId - Optional id of the specific profile resource to retrieve.
* @param {Function(err, profile)} callback - Optional callback to execute on completion of the request
*
* @throws {RequiredParameterError} Argument accessToken required
*
* @see {@link https://build.misfit.com/docs/references#APIReferences-Profile|Misfit - Profile}
* @public
*/
this.getProfile = function (accessToken, options, callback) {
checkRequired(arguments, 'accessToken');
callback = callback || options;
options = options || {};
getResource(accessToken, util.format('%s%s', setup.apiUrl, PATH_RESOURCE_PROFILE), {}, options.userId, options.objectId, callback);
};
/**
* Get the device information for the specified user.
*
* @param {String} accessToken - The user's access token to authenticate the request
* @param {String} options - Optional set of options to configure the request.
* {String} userId - User id of the device resource owner. If not specified assumed to be 'me'
* {String} objectId - Optional id of the specific device resource to retrieve.
* @param {Function(err, device)} callback - Optional callback to execute on completion of the request
*
* @throws {RequiredParameterError} Argument accessToken required
*
* @see {@link https://build.misfit.com/docs/references#APIReferences-Device|Misfit - Device}
* @public
*/
this.getDevice = function (accessToken, options, callback) {
checkRequired(arguments, 'accessToken');
callback = callback || options;
options = options || {};
getResource(accessToken, util.format('%s%s', setup.apiUrl, PATH_RESOURCE_DEVICE), {}, options.userId, options.objectId, callback);
};
/**
* Get the goal information for the specified user.
*
* @param {String} accessToken - The user's access token to authenticate the request
* @param {String} startDate - Start date for the query (YYYY-MM-DD)
* @param {String} endDate - End date for the query (YYYY-MM-DD)
* @param {String} options - Optional set of options to configure the request.
* {String} userId - User id of the goal resource owner. If not specified assumed to be 'me'
* {String} objectId - Optional id of the specific goal resource to retrieve.
* @param {Function(err, goals)} callback - Optional callback to execute on completion of the request
*
* @throws {InvalidDateError} startDate and endDate must be valid dates in the format YYYY-MM-DD
* @throws {InvalidDateRangeError} startDate must precede endDate and the duration may not exceed 30 days
* @throws {RequiredParameterError} Arguments accessToken, startDate, endDate required
*
* @see {@link https://build.misfit.com/docs/references#APIReferences-Goal|Misfit - Goal}
* @public
*/
this.getGoals = function (accessToken, startDate, endDate, options, callback) {
checkRequired(arguments, 'accessToken', 'startDate', 'endDate');
validateDates(startDate, endDate);
callback = callback || options;
options = options || {};
getResource(accessToken, util.format('%s%s', setup.apiUrl, PATH_RESOURCE_GOALS), {
start_date: startDate,
end_date: endDate
}, options.userId, options.objectId, callback);
};
/**
* Get the summary information for the specified user.
*
* @param {String} accessToken - The user's access token to authenticate the request
* @param {String} startDate - Start date for the query (YYYY-MM-DD)
* @param {String} endDate - End date for the query (YYYY-MM-DD)
* @param {String} options - Optional set of options to configure the request.
* {String} userId - User id of the summary owner. If not specified assumed to be 'me'
* {Boolean} detail - Print a summary for each day instead of rolling up the summary to a single entry
* @param {Function(err, summary)} callback - Optional callback to execute on completion of the request
*
* @throws {InvalidDateError} startDate and endDate must be valid dates in the format YYYY-MM-DD
* @throws {InvalidDateRangeError} startDate must precede endDate and the duration may not exceed 30 days
* @throws {RequiredParameterError} Arguments accessToken, startDate, endDate required
*
* @see {@link https://build.misfit.com/docs/references#APIReferences-Summary|Misfit - Summary}
* @public
*/
this.getSummary = function (accessToken, startDate, endDate, options, callback) {
checkRequired(arguments, 'accessToken', 'startDate', 'endDate');
validateDates(startDate, endDate);
callback = callback || options;
options = options || {};
getResource(accessToken, util.format('%s%s', setup.apiUrl, PATH_RESOURCE_SUMMARY), {
start_date: startDate,
end_date: endDate,
detail: options.detail || false
}, options.userId, undefined, callback);
};
/**
* Get the session information for the specified user.
*
* @param {String} accessToken - The user's access token to authenticate the request
* @param {String} startDate - Start date for the query (YYYY-MM-DD)
* @param {String} endDate - End date for the query (YYYY-MM-DD)
* @param {String} options - Optional set of options to configure the request.
* {String} userId - User id of the session resource owner. If not specified assumed to be 'me'
* {String} objectId - Optional id of the specific session resource to retrieve.
* @param {Function(err, sessions)} callback - Optional callback to execute on completion of the request
*
* @throws {InvalidDateError} startDate and endDate must be valid dates in the format YYYY-MM-DD
* @throws {InvalidDateRangeError} startDate must precede endDate and the duration may not exceed 30 days
* @throws {RequiredParameterError} Arguments accessToken, startDate, endDate required
*
* @see {@link https://build.misfit.com/docs/references#APIReferences-Session|Misfit - Session}
* @public
*/
this.getSessions = function (accessToken, startDate, endDate, options, callback) {
checkRequired(arguments, 'accessToken', 'startDate', 'endDate');
validateDates(startDate, endDate);
callback = callback || options;
options = options || {};
getResource(accessToken, util.format('%s%s', setup.apiUrl, PATH_RESOURCE_SESSIONS), {
start_date: startDate,
end_date: endDate
}, options.userId, options.objectId, callback);
};
/**
* Get the sleep information for the specified user.
*
* @param {String} accessToken - The user's access token to authenticate the request
* @param {String} startDate - Start date for the query (YYYY-MM-DD)
* @param {String} endDate - End date for the query (YYYY-MM-DD)
* @param {String} options - Optional set of options to configure the request.
* {String} userId - User id of the sleep resource owner. If not specified assumed to be 'me'
* {String} objectId - Optional id of the specific sleep resource to retrieve.
* @param {Function(err, sleeps)} callback - Optional callback to execute on completion of the request
*
* @throws {InvalidDateError} startDate and endDate must be valid dates in the format YYYY-MM-DD
* @throws {InvalidDateRangeError} startDate must precede endDate and the duration may not exceed 30 days
* @throws {RequiredParameterError} Arguments accessToken, startDate, endDate required
*
* @see {@link https://build.misfit.com/docs/references#APIReferences-Sleep|Misfit - Sleep}
* @public
*/
this.getSleeps = function (accessToken, startDate, endDate, options, callback) {
checkRequired(arguments, 'accessToken', 'startDate', 'endDate');
validateDates(startDate, endDate);
callback = callback || options;
options = options || {};
getResource(accessToken, util.format('%s%s', setup.apiUrl, PATH_RESOURCE_SLEEPS), {
start_date: startDate,
end_date: endDate
}, options.userId, options.objectId, callback);
};
/**
* Handle subscription request from Misfit Cloud API
*
* @param {Object} data - Subscription Amazon SNS message from Misfit Cloud API
* @param {Function(err, sleeps)} callback - Optional callback to execute on completion of the request
*
* @throws {RequiredParameterError} Argument data required
*
* @see {@link https://build.misfit.com/docs/references#APIReferences-Confirmsubscription|Misfit - Confirm subscription}
* @public
*/
this.handleSubscription = function(data, callback) {
checkRequired(arguments, 'data');
request
.get(data.subscribeurl)
.end(function (err, response) {
if(!isFunction(callback)) { return; }
callback(err, response);
});
}
};
return nodeMisfit;
})();
module.exports = NodeMisfit;
module.exports.InvalidDateError = InvalidDateError;
module.exports.InvalidDateRangeError = InvalidDateRangeError;
module.exports.InvalidParameterError = InvalidParameterError;
module.exports.RequiredParameterError = RequiredParameterError;