-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGoogleApi.js
92 lines (83 loc) · 2.19 KB
/
GoogleApi.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
import React, { createContext } from 'react'
import PropTypes from 'prop-types'
import loadScript from '@lourd/load-script'
const {
Provider: GoogleApiProvider,
Consumer: GoogleApiConsumer,
} = createContext(null)
GoogleApiProvider.displayName = 'GoogleApiProvider'
GoogleApiConsumer.displayName = 'GoogleApiConsumer'
class GoogleApi extends React.Component {
static propTypes = {
clientId: PropTypes.string.isRequired,
apiKey: PropTypes.string.isRequired,
discoveryDocs: PropTypes.arrayOf(PropTypes.string).isRequired,
scopes: PropTypes.arrayOf(PropTypes.string).isRequired,
children: PropTypes.oneOfType([PropTypes.func, PropTypes.node]),
}
authorize = () => {
if (this.auth) {
this.auth.signIn()
}
}
signout = () => {
if (this.auth) {
this.auth.signOut()
}
}
state = {
signedIn: false,
client: null,
loading: true,
error: null,
authorize: this.authorize,
signout: this.signout,
}
componentDidMount() {
this.setupApi()
}
async setupApi() {
try {
if (typeof window.gapi === 'undefined') {
await loadScript('https://apis.google.com/js/api.js')
}
if (!gapi.client) {
await new Promise((resolve, reject) =>
gapi.load('client:auth2', {
callback: resolve,
onerror: reject,
}),
)
}
await gapi.client.init({
apiKey: this.props.apiKey,
clientId: this.props.clientId,
discoveryDocs: this.props.discoveryDocs,
scope: this.props.scopes.join(','),
})
} catch (error) {
this.setState({
loading: false,
error,
})
return
}
this.auth = gapi.auth2.getAuthInstance()
this.setState({
client: gapi.client,
loading: false,
signedIn: this.auth.isSignedIn.get(),
})
this.auth.isSignedIn.listen(signedIn => this.setState({ signedIn }))
}
render() {
return (
<GoogleApiProvider value={this.state}>
{typeof this.props.children === 'function'
? this.props.children(this.state)
: this.props.children}
</GoogleApiProvider>
)
}
}
export { GoogleApi, GoogleApiConsumer, GoogleApiProvider }