-
Notifications
You must be signed in to change notification settings - Fork 7
/
GoogleSheetsProvider.js.html
219 lines (180 loc) · 6.87 KB
/
GoogleSheetsProvider.js.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JSDoc: Source: GoogleSheetsProvider.js</title>
<script src="scripts/prettify/prettify.js"> </script>
<script src="scripts/prettify/lang-css.js"> </script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>
<body>
<div id="main">
<h1 class="page-title">Source: GoogleSheetsProvider.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>/**
*
* Google Sheets Provider for the React app
*
* metis <https://github.com/athersharif/metis>
*
* Copyright (c) 2019-Present, Ather Sharif.
* Released under the MIT License.
*
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import flatMap from 'lodash/flatMap';
import DefaultLoadingComponent from './DefaultLoadingComponent';
export const DataContext = React.createContext({
db: null,
error: null,
refetch: null,
});
/**
*
* Provider for the React App
*
* @param {object} [config={}] The config for the HOC
* @param {object} [config.dataLoading={}] The config for the Load Error Component.
* @param {function} [config.dataLoading.component] The custom component to render when loading results from Google Sheets.
* @param {string} [config.dataLoading.className="data-load-error"] The class name of the Component for custom styling and control.
* @param {string} [config.dataLoading.text="Loading..."] The text to display when loading results, rendered as a `P` tag.
*
*/
class GoogleSheetsProvider extends Component {
static propTypes = {
children: PropTypes.node,
config: PropTypes.object,
};
constructor() {
super();
this.state = {
db: null,
error: null,
refetch: this.refetch,
};
}
componentDidMount() {
this.fetchData();
}
/**
*
* Constructs the URL for Google Sheets API. Uses the Google Sheets ID and API key from the `REACT_APP_GOOGLE_SHEETS_DOC_ID` and `REACT_APP_GOOGLE_SHEETS_API_KEY` environment variables respectively. The environment variables should be declared as per the [Create React App guidelines](https://create-react-app.dev/docs/adding-custom-environment-variables/).
*
*/
sheetsApiUrl = `https://sheets.googleapis.com/v4/spreadsheets/${process.env.REACT_APP_GOOGLE_SHEETS_DOC_ID}?includeGridData=true&fields=sheets(data%2FrowData%2Fvalues%2FformattedValue%2Cproperties%2Ftitle)&key=${process.env.REACT_APP_GOOGLE_SHEETS_API_KEY}`;
/**
*
* Constructs the URL for Google Drive API. Uses the Google Sheets ID and API key from the `REACT_APP_GOOGLE_SHEETS_DOC_ID` and `REACT_APP_GOOGLE_SHEETS_API_KEY` environment variables respectively. The environment variables should be declared as per the [Create React App guidelines](https://create-react-app.dev/docs/adding-custom-environment-variables/).
*
*/
driveApiUrl = `https://www.googleapis.com/drive/v3/files/${process.env.REACT_APP_GOOGLE_SHEETS_DOC_ID}?fields=modifiedTime&key=${process.env.REACT_APP_GOOGLE_SHEETS_API_KEY}`;
/**
* Fetches Google Sheets data by first checking when it was modified. If it was modified before the last check then pulls the data from localStorage otherwise makes a network call to Google Sheets API. Helpful when processing large amount of Sheets data.
*/
fetchData = () => {
let lastCheckedAt = window.localStorage.getItem('metisLastCheckedAt');
if (lastCheckedAt == null || this.state.db === null) this.fetchSheetData();
else {
fetch(this.driveApiUrl)
.then((response) => response.json())
.then(({ modifiedTime }) => {
const lastModified = Date.parse(modifiedTime);
if (lastCheckedAt < lastModified) this.fetchSheetData();
})
.catch((error) => console.error(error));
}
window.localStorage.setItem('metisLastCheckedAt', Date.now());
};
fetchSheetData = () => {
fetch(this.sheetsApiUrl)
.then((response) => response.json())
.then((data) => {
if (data.error) {
this.setState({ error: data.error });
} else {
this.setState({ db: this.processData(data) });
}
})
.catch((error) => console.error(error));
};
refetch = () => this.fetchData();
/**
*
* Processes the raw data from the Google Sheets API into a readable key/value format accessible via `withGoogleSheets` HOC.
*
* @param {object} data
* @param {array} data.sheets Raw sheets data from the Google Sheets API
*
*/
processData = ({ sheets }) => {
let result = {};
sheets.forEach((sheet) => {
const {
properties: { title: id },
data,
} = sheet;
if (data[0].rowData) {
let [headerRow, ...records] = data[0].rowData;
headerRow = flatMap(headerRow.values, (row) => row.formattedValue);
result = {
...result,
[id]: records.map((record) => {
let result = {};
headerRow.forEach((value, index) => {
result = {
[value]: record.values[index]
? record.values[index].formattedValue
: null,
...result,
};
});
return result;
}),
};
} else {
result = {
...result,
[id]: null,
};
}
});
return result;
};
render() {
const { config } = this.props;
const loadingComponentConfig =
config && config.dataLoading ? config.dataLoading : {};
const LoadingComponent = loadingComponentConfig.component
? loadingComponentConfig.component
: DefaultLoadingComponent;
return this.state.db || this.state.error ? (
<DataContext.Provider value={this.state}>
{this.props.children}
</DataContext.Provider>
) : (
<LoadingComponent config={loadingComponentConfig} />
);
}
}
export default GoogleSheetsProvider;
</code></pre>
</article>
</section>
</div>
<nav>
<h2><a href="index.html">Home</a></h2><h3>Classes</h3><ul><li><a href="GoogleSheetsProvider.html">GoogleSheetsProvider</a></li></ul><h3>Global</h3><ul><li><a href="global.html#DEFAULTS">DEFAULTS</a></li><li><a href="global.html#DefaultLoadErrorComponent">DefaultLoadErrorComponent</a></li><li><a href="global.html#DefaultLoadingComponent">DefaultLoadingComponent</a></li><li><a href="global.html#withGoogleSheets">withGoogleSheets</a></li></ul>
</nav>
<br class="clear">
<footer>
Documentation generated by <a href="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/jsdoc/jsdoc">JSDoc 4.0.2</a> on Sat Apr 08 2023 01:58:57 GMT-0700 (Pacific Daylight Time)
</footer>
<script> prettyPrint(); </script>
<script src="scripts/linenumber.js"> </script>
</body>
</html>