-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGoogleApiApp.js
307 lines (291 loc) · 10.1 KB
/
GoogleApiApp.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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/**
* GitHub https://github.com/tanaikech/GoogleApiApp<br>
* Library name
* @type {string}
* @const {string}
* @readonly
*/
var appName = "GoogleApiApp";
/**
* ### Description
* Set information of Google API you want to use.
*
* @param {Object} object Object for using a Google API.
* @return {GoogleApiApp}
*/
function setAPIInf(object = {}) {
this.apiInf = object;
return this;
}
/**
* ### Description
* Set parameters for using Google API you want to use. This object includes as follows.
* `path`: Object Ex. fileId. This value is used in the endpoint.
* `query`: Object Ex. fields. This value is used in the query parameter of the endpoint.
* `requestBody`: Object Ex. {name: "sample title"}. This value is used as the request body of the API.
* `usePageToken`: Boolean When this is true, the response value is retrieved with pageToken. Default value is false.
*
* @param {Object} object Object including parameters for using a Google API.
* @return {GoogleApiApp}
*/
function setAPIParams(object = {}) {
this.apiParams = object;
return this;
}
/**
* ### Description
* Set access token. When you are required to use the specific access token, please use this method. When the API key is not used, this access token is used. If the API key is not used and this methos is not used, the access token retrieved by `ScriptApp.getOAuthToken()` is used.
*
* For example, if you want to use the access token retrieved from the service account. Please set the access token using this method.
*
* @param {String} accessToken
* @return {GoogleApiApp}
*/
function setAccessToken(accessToken) {
this.accessToken = accessToken;
return this;
}
/**
* ### Description
* Get information of Google API.
*
* @returns {String[]} Returned information of API.
*/
function getAPI() {
const object = { apiInf: this.apiInf, apiParams: this.apiParams, accessToken: this.accessToken };
return new GoogleApiApp_(object).getAPI();
}
/**
* ### Description
* Request Google API.
*
* @returns {UrlFetchApp.HTTPResponse|String[]} Response from API. When pageToken is used, String[] is returned.
*/
function request() {
const object = { apiInf: this.apiInf, apiParams: this.apiParams, accessToken: this.accessToken };
return new GoogleApiApp_(object).request();
}
/**
*
*/
class GoogleApiApp_ {
/**
* @param {Object} object Object using this library.
*/
constructor(object) {
this.obj = JSON.parse(JSON.stringify(object));
this.discoveryUrl = "https://discovery.googleapis.com/discovery/v1/apis";
this.apiUrl = "";
this.token = "";
}
/**
* ### Description
* Get information of API.
*
* @returns {String[]} Returned information of API.
*/
getAPI() {
this.errorCheck_(false);
this.getAPImethods_(this.obj);
return this.obj.messages;
}
/**
* ### Description
* Request Google API.
*
* @returns {UrlFetchApp.HTTPResponse|String[]} Response from API. When pageToken is used, String[] is returned.
*/
request() {
this.errorCheck_(true);
this.getAPImethods_(this.obj);
if (this.obj.apiParams.hasOwnProperty("usePageToken") && this.obj.apiParams.usePageToken === true && this.obj.apiObj?.parameters?.pageToken) {
return this.getList_(this.obj);
}
return this.normalRequest_(this.obj);
}
/**
* ### Description
* Check errors of inputted object.
*/
errorCheck_(c) {
const k = ["api", "version", "methodName"];
if (!this.obj.apiInf || !k.every(e => this.obj.apiInf.hasOwnProperty(e))) {
throw new Error("Invalid object. Please confirm it again.");
}
if (c) {
if (!this.obj.apiParams) {
this.obj.apiParams = { query: {} };
} else if (this.obj.apiParams && !this.obj.apiParams.query) {
this.obj.apiParams.query = {};
}
if (!this.obj.apiParams.query.hasOwnProperty("key")) {
this.token = this.obj.accessToken || ScriptApp.getOAuthToken();
}
}
}
/**
* ### Description
* Get discovery rest URL.
*
* @param {Object} object { api, version } Name of API and version
* @returns {Object} Discovery rest URL and information of API.
*/
getAPI_({ api, version }) {
const { items } = JSON.parse(this.fetch_({ url: `${this.discoveryUrl}?fields=*&name=${api}` }).getContentText())
if (!items) {
throw new Error("Invalid values are returned.");
}
const r = items.find(e => e.name == api.toLocaleLowerCase() && e.version == version);
if (!r) {
throw new Error("Inputted API was not found. Please confirm your inputted values again.");
}
const messages = [
`Discovery rest URL is ${r.discoveryRestUrl}`,
`Please enable ${r.title} ${r.version} at Advanced Google services or API console.`,
`The link of official document is ${r.documentationLink}.`
];
return { url: r.discoveryRestUrl, messages };
}
/**
* ### Description
* Get method of API.
*
* @param {Object} obj Object about the information of API.
*/
getAPImethods_(obj) {
const { apiInf: { api, version, methodName } } = obj
const path = obj.apiParams?.path;
const { url, messages } = this.getAPI_({ api, version });
obj.url1 = url;
obj.messages = messages;
const { baseUrl, resources } = JSON.parse(this.fetch_({ url }).getContentText());
const [resource, ...ar] = methodName.trim().split(".");
let r = resources[resource];
let out = null;
for (let i = 0; i < ar.length; i++) {
if (r.methods && r.methods.hasOwnProperty(ar[i])) {
out = r.methods[ar[i]];
break;
} else if (r.resources && r.resources.hasOwnProperty(ar[i])) {
r = r.resources[ar[i]];
}
}
if (out === null) {
throw new Error("Please set valid methodName. Ex. files.list, comments.list, users.settings.sendAs.smimeInfo.get and so on.");
}
obj.messages.push(
`Please add one or several scopes from ${out.scopes.join(", ")}.`,
out.description.trim()
);
this.apiUrl = `${baseUrl}${out.path}`;
if (path) {
Object.entries(path).forEach(([k, v]) => {
const reg = new RegExp(`{.*${k}.*}`);
this.apiUrl = this.apiUrl.replace(reg, v);
});
}
obj.apiObj = out;
}
/**
* ### Description
* Request Google API.
*
* @param {Object} object Object for requesting API.
* @returns {UrlFetchApp.HTTPResponse} Response from API.
*/
normalRequest_(object) {
const { apiParams, apiObj } = object;
const url = this.addQuery(this.apiUrl, apiParams.query);
const req = { url, muteHttpExceptions: true, method: apiObj.httpMethod };
if (apiParams.requestBody && typeof apiParams.requestBody == "object") {
req.payload = JSON.stringify(apiParams.requestBody);
req.contentType = "application/json";
}
if (this.token) {
req.headers = { authorization: "Bearer " + this.token };
}
const res = this.fetch_(req);
if (res.getResponseCode() != 200) {
console.log(object.messages.join("\n"));
throw new Error(res.getContentText());
}
return res;
}
/**
* ### Description
* Request Google API with pageToken.
*
* @param {Object} object Object for requesting API.
* @returns {String[]} Response from API using pageToken.
*/
getList_(object) {
let { apiParams, apiObj } = object;
if (apiParams.query && apiParams.query.fields && !apiParams.query.fields.includes("nextPageToken")) {
apiParams.query.fields += ",nextPageToken";
}
const p = ["maxResults", "pageSize"].find(e => apiObj.parameters[e]);
if (apiObj.parameters[p]?.maximum && apiObj.parameters[p]?.maximum > 0) {
apiParams.query[p] = apiObj.parameters[p].maximum;
} else {
console.log("The maximum 'pageSize' is not found. So, this request uses the default pageSize. If you know the maximum pageSize in this API, please include it in 'query'.");
}
let pageToken = "";
const items = [];
let numberOfPages = 1;
do {
console.log(`Page ${numberOfPages}`);
const url = this.addQuery(this.apiUrl, apiParams.query);
const req = { url, muteHttpExceptions: true, method: apiObj.httpMethod };
if (this.token) {
req.headers = { authorization: "Bearer " + this.token };
}
const res = this.fetch_(req);
if (res.getResponseCode() != 200) {
console.log(object.messages.join("\n"))
throw new Error(res.getContentText());
}
const o = JSON.parse(res.getContentText());
const ar = Object.values(o).find(e => typeof e == "object" && Array.isArray(e) && e.length > 0);
if (ar && ar.length > 0) {
items.push(...ar);
}
console.log(`Current number of list items ${items.length}`);
pageToken = o.nextPageToken;
apiParams.query.pageToken = pageToken;
numberOfPages++;
} while (pageToken);
console.log(`Total number of pages is ${numberOfPages}.`);
return items;
}
/**
* ### Description
* Add query parameter to the endpoint.
* ref: https://github.com/tanaikech/UtlApp?tab=readme-ov-file#addqueryparameters
*
* @param {String} url Endpoint
* @param {Object} query Query parameters.
* @returns {String} Endpoint including the query parameters.
*/
addQuery(url, query) {
String.prototype.addQuery = function (o) {
return (this == "" ? "" : `${this}?`) + Object.entries(o).flatMap(([k, v]) => Array.isArray(v) ? v.map(e => `${k}=${encodeURIComponent(e)}`) : `${k}=${encodeURIComponent(v)}`).join("&");
}
return url.addQuery(query);
}
/**
* ### Description
* Add query parameter to the endpoint.
* ref: https://github.com/tanaikech/UtlApp?tab=readme-ov-file#addqueryparameters
*
* @param {Object} obj Object for using UrlFetchApp.fetchAll.
* @returns {UrlFetchApp.HTTPResponse} Response from API.
*/
fetch_(obj) {
obj.muteHttpExceptions = true;
const res = UrlFetchApp.fetchAll([obj])[0];
if (res.getResponseCode() != 200) {
throw new Error(res.getContentText());
}
return res;
}
}