-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathgapi.js
197 lines (179 loc) · 6.26 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
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
/*******************************************************************************
*
* GAPI WRAPPER
*
******************************************************************************/
/**
* Exposes methods related to the Google API Client and Auth modules.
* As they are a part of the gapi object, each method returns
* always a promise because it always calls it through its loader,
* to be sure to properly load things it if ir's not present.
* In the same manner, because things could change between two calls and
* as the Google's guidelines suggest, the client and auth objects are
* initialized for each call, and as this is done asynchronously it enforces
* the promise response.
*/
/**
* It has been done through a class definition for two reasons :
* * It's easier to bind this to the good things from inside a class
* * It allows to easily extend the class by inheritance (or its JS mimic...)
* * It also allows to instanciate, if needed, more than one GAPI in the same
* application, with different config for some edge cases.
*/
const timeout = 5000
const gapiUrl = 'https://apis.google.com/js/api.js'
/** Formats a GoogleUser basic profile object to something readable */
function _formatUser (guser) {
if (!guser.getBasicProfile) return null
const profile = guser.getBasicProfile()
return {
id: profile.getId(),
name: profile.getName(),
firstname: profile.getGivenName(),
lastname: profile.getFamilyName(),
image: profile.getImageUrl(),
email: profile.getEmail()
}
}
/** Get the response object from the user's auth session. */
function _formatAuthObject (guser) {
if (!guser.getAuthResponse) return null
return guser.getAuthResponse()
}
export default class GAPI {
/**
* The constructor expect as parameter the config object, containing
* API key, Cliend Id, the scope and the Google's discovery docs, as
* it's defined at :
* https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiclientinitargs
*/
constructor (config) {
this.config = config
}
/** Exposes the gapi object, loading the script and attaching it to
* document's head if it hasn't been done */
_load () {
// resolves immediately if already loaded
if (window.gapi) return Promise.resolve(window.gapi)
// otherwise prepares and loads
return new Promise((resolve, reject) => {
const script = document.createElement('script')
script.src = gapiUrl
let limit = setTimeout(() => {
// reject promise in case of a timeout.
script.remove()
reject(new Error('gapi load timeout.'))
}, timeout)
document.head.appendChild(script)
// defines the callback that resolves on successful load
script.onload = () => {
clearTimeout(limit)
// let's reject if the global gapi object has not been created
if (!window.gapi) reject(new Error('gapi load error.'))
// otherwise, everything is ok, resolves
resolve(window.gapi)
}
})
}
/** Exposes a gapi library object, loading it if it hasn't been done */
_libraryLoad (lib) {
return this._load()
.then(gapi => {
if (gapi[lib]) return Promise.resolve(gapi[lib])
return new Promise((resolve, reject) => {
gapi.load(lib, {
timeout: timeout,
callback: () => {
resolve(gapi[lib])
},
onerror: err => {
reject(new Error(`Error on gapi ${lib} load: ${err.message}`))
},
ontimeout: () => {
reject(new Error(`Error on gapi ${lib} load: timeout`))
}
})
})
})
}
/** Initialize a gapi library object with config before each API call.
* Return the library object through a Promise. */
_libraryInit (lib, config = {}) {
// fills omitted parameters wit hmain config ones if needed
config.apiKey = config.apiKey || this.config.apiKey
config.clientId = config.clientId || this.config.clientId
config.scope = config.scope || this.config.scope
config.discoveryDocs = config.discoveryDocs || this.config.discoveryDocs
return this._libraryLoad(lib)
.then(library => {
return library.init(config)
.then(response => {
// if auth2, returns the google auth object, the library otherwise
return Promise.resolve((lib === 'auth2') ? response : library)
}, () => {
return Promise.reject(new Error(`Error on gapi ${lib} init.`))
})
})
}
/** returns asynchronously true if the user is signed in */
isSignedIn () {
return this._libraryInit('auth2')
.then(auth => {
return Promise.resolve(auth.isSignedIn.get())
})
}
/** returns the current user auth data if signed in, undefined otherwise */
getAuthObject () {
return this._libraryInit('auth2')
.then(auth => {
if (auth.isSignedIn.get()) {
return Promise.resolve(_formatAuthObject(auth.currentUser.get()))
} else {
return Promise.resolve(null)
}
})
}
/** returns the current user if signed in, undefined otherwise */
currentUser () {
return this._libraryInit('auth2')
.then(auth => {
if (auth.isSignedIn.get()) {
return Promise.resolve(_formatUser(auth.currentUser.get()))
} else {
return Promise.resolve(null)
}
})
}
/** Starts the signin process - returns a promise resolved with the user if
* signin successfull, or rejected otherwise */
signIn (options) {
return this._libraryInit('auth2')
.then(auth => {
if (auth.isSignedIn.get()) {
return Promise.resolve(_formatUser(auth.currentUser.get()))
} else {
return auth.signIn(options)
.then(guser => {
return Promise.resolve(_formatUser(guser))
})
}
})
}
/** Disconnects the current user */
signOut () {
return this._libraryInit('auth2')
.then(auth => {
if (auth.isSignedIn.get()) {
auth.disconnect()
}
return Promise.resolve()
})
}
/** Makes a generic API request */
request (args) {
return this._libraryInit('client')
.then(client => {
return client.request(args)
})
}
}