/
gapi.js
110 lines (87 loc) · 2.61 KB
/
gapi.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
define(['config'], function(config) {
var app;
function ApiManager(_app) {
app = _app;
this.loadGapi();
}
_.extend(ApiManager.prototype, Backbone.Events);
ApiManager.prototype.init = function() {
var self = this;
gapi.client.load('tasks', 'v1', function() { /* Loaded */ });
function handleClientLoad() {
gapi.client.setApiKey(config.apiKey);
window.setTimeout(checkAuth, 100);
}
function checkAuth() {
gapi.auth.authorize({ client_id: config.clientId, scope: config.scopes, immediate: true }, handleAuthResult);
}
function handleAuthResult(authResult) {
var authTimeout;
if (authResult && !authResult.error) {
// Schedule a check when the authentication token expires
if (authResult.expires_in) {
authTimeout = (authResult.expires_in - 5 * 60) * 1000;
setTimeout(checkAuth, authTimeout);
}
app.views.auth.$el.hide();
$('#signed-in-container').show();
self.trigger('ready');
} else {
if (authResult && authResult.error) {
// TODO: Show error
console.error('Unable to sign in:', authResult.error);
}
app.views.auth.$el.show();
}
}
this.checkAuth = function() {
gapi.auth.authorize({ client_id: config.clientId, scope: config.scopes, immediate: false }, handleAuthResult);
};
handleClientLoad();
};
ApiManager.prototype.loadGapi = function() {
var self = this;
// Don't load gapi if it's already present
if (typeof gapi !== 'undefined') {
return this.init();
}
require(['https://apis.google.com/js/client.js?onload=define'], function() {
// Poll until gapi is ready
function checkGAPI() {
if (gapi && gapi.client) {
self.init();
} else {
setTimeout(checkGAPI, 100);
}
}
checkGAPI();
});
};
Backbone.sync = function(method, model, options) {
options || (options = {});
switch (method) {
case 'create':
break;
case 'update':
break;
case 'delete':
break;
case 'read':
request = gapi.client.tasks[model.url].list(options.data);
Backbone.gapiRequest(request, method, model, options);
break;
}
};
Backbone.gapiRequest = function(request, method, model, options) {
var result;
request.execute(function(res) {
if (res.error) {
if (options.error) options.error(res);
} else if (options.success) {
result = res.items;
options.success(result, true, request);
}
});
};
return ApiManager;
});