-
Notifications
You must be signed in to change notification settings - Fork 30
/
google-api-async.js
79 lines (65 loc) · 2.45 KB
/
google-api-async.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
// kill logs
var Log = function () {}
GoogleApi = {
// host component, shouldn't change
_host: 'https://www.googleapis.com',
_callAndRefresh: function(method, path, options, callback) {
var self = this;
options = options || {};
self._call(method, path, options,
// need to bind the env here so we can do mongo writes in the callback
// (when refreshing), if we call this on the server
Meteor.bindEnvironment(function(error, result) {
if (error && error.response && error.response.statusCode == 401) {
Log('google-api attempting token refresh');
return self._refresh(options.user, function(error) {
if (error)
return callback(error);
// if we have the user, we'll need to re-fetch them, as their
// access token will have changed.
if (options.user)
options.user = Meteor.users.findOne(options.user._id);
self._call(method, path, options, callback);
});
} else {
callback(error, result);
}
}, 'Google Api callAndRefresh'));
},
// call a GAPI Meteor.http function if the accessToken is good
_call: function(method, path, options, callback) {
Log('GoogleApi._call, path:' + path);
// copy existing options to modify
options = _.extend({}, options)
var user = options.user || Meteor.user();
delete options.user;
if (user && user.services && user.services.google &&
user.services.google.accessToken) {
options.headers = options.headers || {};
options.headers.Authorization = 'Bearer ' + user.services.google.accessToken;
HTTP.call(method, this._host + '/' + path, options, function(error, result) {
callback(error, result && result.data);
});
} else {
callback(new Meteor.Error(403, "Auth token not found." +
"Connect your google account"));
}
},
_refresh: function(user, callback) {
Log('GoogleApi._refresh');
Meteor.call('exchangeRefreshToken', user && user._id, function(error, result) {
callback(error, result && result.access_token)
});
}
}
// setup HTTP verbs
httpVerbs = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'];
_.each(httpVerbs, function(verb) {
GoogleApi[verb.toLowerCase()] = wrapAsync(function(path, options, callback) {
if (_.isFunction(options)) {
callback = options;
options = {};
}
return this._callAndRefresh(verb, path, options, callback);
})
});