@gzhangx/googleapi 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +2 -0
- package/lib/googleApi.d.ts +31 -0
- package/lib/googleApi.js +316 -0
- package/lib/index.d.ts +2 -0
- package/lib/index.js +7 -0
- package/package.json +27 -0
- package/pub.bat +2 -0
- package/src/googleApi.ts +249 -0
- package/src/index.ts +3 -0
- package/test.bat +2 -0
- package/tsconfig.json +15 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 gzhangx
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export interface IRefresCreds {
|
|
2
|
+
refresh_token: string;
|
|
3
|
+
client_id: string;
|
|
4
|
+
client_secret: string;
|
|
5
|
+
}
|
|
6
|
+
export declare function getFormData(obj: {
|
|
7
|
+
[id: string]: any;
|
|
8
|
+
}): (string | null);
|
|
9
|
+
interface IIdRange {
|
|
10
|
+
id: string;
|
|
11
|
+
range: string;
|
|
12
|
+
}
|
|
13
|
+
declare type IAppendFunc = (idRng: IIdRange, data: any, opts?: any) => Promise<any>;
|
|
14
|
+
declare type IReadFunc = (idRng: IIdRange) => Promise<any>;
|
|
15
|
+
export interface IGoogleClient {
|
|
16
|
+
access_token: string;
|
|
17
|
+
expires_on: number;
|
|
18
|
+
token_type: string;
|
|
19
|
+
doBatchUpdate: (id: string, data: any) => Promise<any>;
|
|
20
|
+
append: IAppendFunc;
|
|
21
|
+
read: IReadFunc;
|
|
22
|
+
getSheeOps: (id: string) => {
|
|
23
|
+
doBatchUpdate: (data: any) => Promise<any>;
|
|
24
|
+
append: (range: string, data: any, opts?: any) => Promise<any>;
|
|
25
|
+
read: (range: string) => Promise<any>;
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
export declare function getClient(creds: IRefresCreds): Promise<IGoogleClient>;
|
|
29
|
+
export declare function getClientByEnv(envName: string): Promise<IGoogleClient>;
|
|
30
|
+
export declare function test(d: boolean): Promise<void>;
|
|
31
|
+
export {};
|
package/lib/googleApi.js
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
//rootUrl = 'https://accounts.google.com/o/oauth2/v2/auth';
|
|
3
|
+
//opts = { access_type: 'offline', scope: 'https://www.googleapis.com/auth/spreadsheets', response_type: 'code', client_id: 'client_id', redirect_uri: 'urn:ietf:wg:oauth:2.0:oob' }
|
|
4
|
+
//return rootUrl + '?' + querystring.stringify(opts);
|
|
5
|
+
//'https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fspreadsheets&response_type=code&client_id=client_id&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob'
|
|
6
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
7
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
8
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
9
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
10
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
11
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
12
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
13
|
+
});
|
|
14
|
+
};
|
|
15
|
+
var __generator = (this && this.__generator) || function (thisArg, body) {
|
|
16
|
+
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
|
|
17
|
+
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
|
18
|
+
function verb(n) { return function (v) { return step([n, v]); }; }
|
|
19
|
+
function step(op) {
|
|
20
|
+
if (f) throw new TypeError("Generator is already executing.");
|
|
21
|
+
while (_) try {
|
|
22
|
+
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
|
23
|
+
if (y = 0, t) op = [op[0] & 2, t.value];
|
|
24
|
+
switch (op[0]) {
|
|
25
|
+
case 0: case 1: t = op; break;
|
|
26
|
+
case 4: _.label++; return { value: op[1], done: false };
|
|
27
|
+
case 5: _.label++; y = op[1]; op = [0]; continue;
|
|
28
|
+
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
|
29
|
+
default:
|
|
30
|
+
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
|
31
|
+
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
|
32
|
+
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
|
33
|
+
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
|
34
|
+
if (t[2]) _.ops.pop();
|
|
35
|
+
_.trys.pop(); continue;
|
|
36
|
+
}
|
|
37
|
+
op = body.call(thisArg, _);
|
|
38
|
+
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
|
39
|
+
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
43
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
44
|
+
};
|
|
45
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
46
|
+
exports.test = exports.getClientByEnv = exports.getClient = exports.getFormData = void 0;
|
|
47
|
+
var axios_1 = __importDefault(require("axios"));
|
|
48
|
+
function getFormData(obj) {
|
|
49
|
+
if (!obj)
|
|
50
|
+
return null;
|
|
51
|
+
var keys = Object.keys(obj);
|
|
52
|
+
var data = keys.map(function (key) {
|
|
53
|
+
var v = obj[key];
|
|
54
|
+
if (typeof v === 'number')
|
|
55
|
+
v = '' + v;
|
|
56
|
+
return "".concat(key, "=").concat(encodeURIComponent(obj[key]));
|
|
57
|
+
}).join('&');
|
|
58
|
+
return data;
|
|
59
|
+
}
|
|
60
|
+
exports.getFormData = getFormData;
|
|
61
|
+
function doRefresh(creds) {
|
|
62
|
+
return __awaiter(this, void 0, void 0, function () {
|
|
63
|
+
var refresh_token, client_id, client_secret, dataStr, refreshBody, access_token, expires_in, token_type, doOp, doPost, doBatchUpdate, append, read;
|
|
64
|
+
var _this = this;
|
|
65
|
+
return __generator(this, function (_a) {
|
|
66
|
+
switch (_a.label) {
|
|
67
|
+
case 0:
|
|
68
|
+
refresh_token = creds.refresh_token, client_id = creds.client_id, client_secret = creds.client_secret;
|
|
69
|
+
dataStr = getFormData({
|
|
70
|
+
client_secret: client_secret,
|
|
71
|
+
client_id: client_id,
|
|
72
|
+
refresh_token: refresh_token,
|
|
73
|
+
grant_type: 'refresh_token'
|
|
74
|
+
});
|
|
75
|
+
return [4 /*yield*/, axios_1.default.post('https://oauth2.googleapis.com/token', dataStr, { headers: { "Content-Type": "application/x-www-form-urlencoded" } }).then(function (r) {
|
|
76
|
+
return r.data;
|
|
77
|
+
})];
|
|
78
|
+
case 1:
|
|
79
|
+
refreshBody = _a.sent();
|
|
80
|
+
access_token = refreshBody.access_token, expires_in = refreshBody.expires_in, token_type = refreshBody.token_type;
|
|
81
|
+
doOp = function (op, id, postFix, data) {
|
|
82
|
+
return (0, axios_1.default)({
|
|
83
|
+
url: "https://sheets.googleapis.com/v4/spreadsheets/".concat(id).concat(postFix),
|
|
84
|
+
headers: {
|
|
85
|
+
"Content-Type": "application/json",
|
|
86
|
+
"Authorization": "Bearer ".concat(access_token),
|
|
87
|
+
},
|
|
88
|
+
method: op,
|
|
89
|
+
data: data,
|
|
90
|
+
}).then(function (r) {
|
|
91
|
+
return (r.data);
|
|
92
|
+
});
|
|
93
|
+
};
|
|
94
|
+
doPost = function (id, postFix, data) { return doOp('post', id, postFix, data); };
|
|
95
|
+
doBatchUpdate = function (id, data) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
|
|
96
|
+
return [2 /*return*/, doPost(id, ':batchUpdate', data)];
|
|
97
|
+
}); }); };
|
|
98
|
+
append = function (_a, data, opts) {
|
|
99
|
+
var id = _a.id, range = _a.range;
|
|
100
|
+
return __awaiter(_this, void 0, void 0, function () {
|
|
101
|
+
return __generator(this, function (_b) {
|
|
102
|
+
switch (_b.label) {
|
|
103
|
+
case 0:
|
|
104
|
+
if (!opts) {
|
|
105
|
+
opts = {};
|
|
106
|
+
}
|
|
107
|
+
if (!opts.valueInputOption)
|
|
108
|
+
opts.valueInputOption = 'USER_ENTERED';
|
|
109
|
+
return [4 /*yield*/, doPost(id, "/values/".concat(range, ":append?").concat(getFormData(opts)), { values: data })];
|
|
110
|
+
case 1: return [2 /*return*/, _b.sent()];
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
};
|
|
115
|
+
read = function (_a) {
|
|
116
|
+
var id = _a.id, range = _a.range;
|
|
117
|
+
return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_b) {
|
|
118
|
+
return [2 /*return*/, doOp('get', id, "/values/".concat(range))];
|
|
119
|
+
}); });
|
|
120
|
+
};
|
|
121
|
+
return [2 /*return*/, {
|
|
122
|
+
access_token: access_token,
|
|
123
|
+
expires_on: new Date().getTime() + (expires_in * 1000 - 2000),
|
|
124
|
+
token_type: token_type,
|
|
125
|
+
doBatchUpdate: doBatchUpdate,
|
|
126
|
+
append: append,
|
|
127
|
+
read: read,
|
|
128
|
+
getSheeOps: function (id) {
|
|
129
|
+
return {
|
|
130
|
+
doBatchUpdate: function (data) { return doBatchUpdate(id, data); },
|
|
131
|
+
append: function (range, data, ops) { return append({ id: id, range: range }, data, ops); },
|
|
132
|
+
read: function (range) { return read({ id: id, range: range }); },
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
}];
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
var clients = {};
|
|
141
|
+
function getClient(creds) {
|
|
142
|
+
return __awaiter(this, void 0, void 0, function () {
|
|
143
|
+
var name, client, now;
|
|
144
|
+
return __generator(this, function (_a) {
|
|
145
|
+
switch (_a.label) {
|
|
146
|
+
case 0:
|
|
147
|
+
name = creds.client_id;
|
|
148
|
+
client = clients[name];
|
|
149
|
+
now = new Date().getTime();
|
|
150
|
+
if (!(!client || client.expires_on <= now)) return [3 /*break*/, 2];
|
|
151
|
+
return [4 /*yield*/, doRefresh(creds)];
|
|
152
|
+
case 1:
|
|
153
|
+
client = _a.sent();
|
|
154
|
+
if (!client)
|
|
155
|
+
return [2 /*return*/, null];
|
|
156
|
+
clients[name] = client;
|
|
157
|
+
_a.label = 2;
|
|
158
|
+
case 2: return [2 /*return*/, client];
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
exports.getClient = getClient;
|
|
164
|
+
function getClientByEnv(envName) {
|
|
165
|
+
return __awaiter(this, void 0, void 0, function () {
|
|
166
|
+
var creds;
|
|
167
|
+
return __generator(this, function (_a) {
|
|
168
|
+
creds = {
|
|
169
|
+
client_id: process.env["google.".concat(envName, ".client_id")],
|
|
170
|
+
client_secret: process.env["google.".concat(envName, ".client_secret")],
|
|
171
|
+
refresh_token: process.env["google.".concat(envName, ".refresh_token")],
|
|
172
|
+
};
|
|
173
|
+
return [2 /*return*/, getClient(creds)];
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
exports.getClientByEnv = getClientByEnv;
|
|
178
|
+
function test(d) {
|
|
179
|
+
return __awaiter(this, void 0, void 0, function () {
|
|
180
|
+
var cli, id, upres, appres, rres, sheet, _a, _b;
|
|
181
|
+
return __generator(this, function (_c) {
|
|
182
|
+
switch (_c.label) {
|
|
183
|
+
case 0: return [4 /*yield*/, getClientByEnv('gzprem')];
|
|
184
|
+
case 1:
|
|
185
|
+
cli = _c.sent();
|
|
186
|
+
if (!cli)
|
|
187
|
+
return [2 /*return*/, console.log('failed to get client')];
|
|
188
|
+
id = '1MO27odjCsxk6MWL0DygubU53hrtt3OB8SEnqjpUHJ-U';
|
|
189
|
+
if (d)
|
|
190
|
+
return [2 /*return*/];
|
|
191
|
+
console.log('do batch update');
|
|
192
|
+
return [4 /*yield*/, cli.doBatchUpdate(id, {
|
|
193
|
+
"requests": [
|
|
194
|
+
{
|
|
195
|
+
"updateDimensionProperties": {
|
|
196
|
+
"range": {
|
|
197
|
+
"sheetId": 0,
|
|
198
|
+
"dimension": "COLUMNS",
|
|
199
|
+
"startIndex": 0,
|
|
200
|
+
"endIndex": 1
|
|
201
|
+
},
|
|
202
|
+
"properties": {
|
|
203
|
+
"pixelSize": 160
|
|
204
|
+
},
|
|
205
|
+
"fields": "pixelSize"
|
|
206
|
+
},
|
|
207
|
+
}
|
|
208
|
+
]
|
|
209
|
+
})];
|
|
210
|
+
case 2:
|
|
211
|
+
_c.sent();
|
|
212
|
+
console.log('do batch update 2');
|
|
213
|
+
return [4 /*yield*/, cli.doBatchUpdate(id, {
|
|
214
|
+
"requests": [
|
|
215
|
+
{
|
|
216
|
+
"updateCells": {
|
|
217
|
+
"fields": "*",
|
|
218
|
+
"range": {
|
|
219
|
+
"sheetId": 0,
|
|
220
|
+
"startColumnIndex": 0,
|
|
221
|
+
"endColumnIndex": 10,
|
|
222
|
+
"startRowIndex": 0,
|
|
223
|
+
"endRowIndex": 10
|
|
224
|
+
},
|
|
225
|
+
"rows": [
|
|
226
|
+
{
|
|
227
|
+
"values": [
|
|
228
|
+
{
|
|
229
|
+
"userEnteredFormat": {
|
|
230
|
+
"backgroundColor": {
|
|
231
|
+
"blue": 10,
|
|
232
|
+
"green": 10,
|
|
233
|
+
"red": 255
|
|
234
|
+
},
|
|
235
|
+
"borders": {
|
|
236
|
+
"bottom": {
|
|
237
|
+
"style": "SOLID",
|
|
238
|
+
"width": 8,
|
|
239
|
+
"color": {
|
|
240
|
+
"blue": 0,
|
|
241
|
+
"green": 255,
|
|
242
|
+
"red": 0
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
},
|
|
247
|
+
"userEnteredValue": { "stringValue": "strstsdfasdf" }
|
|
248
|
+
},
|
|
249
|
+
{
|
|
250
|
+
"userEnteredValue": { "stringValue": "col1" }
|
|
251
|
+
}
|
|
252
|
+
]
|
|
253
|
+
}
|
|
254
|
+
]
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
]
|
|
258
|
+
})];
|
|
259
|
+
case 3:
|
|
260
|
+
upres = _c.sent();
|
|
261
|
+
console.log(upres);
|
|
262
|
+
console.log('append 1');
|
|
263
|
+
return [4 /*yield*/, cli.append({
|
|
264
|
+
id: id,
|
|
265
|
+
range: "'Sheet1'!A1:B2"
|
|
266
|
+
}, [
|
|
267
|
+
['aaa', 'bbb1']
|
|
268
|
+
])];
|
|
269
|
+
case 4:
|
|
270
|
+
appres = _c.sent();
|
|
271
|
+
console.log('append res');
|
|
272
|
+
console.log(appres);
|
|
273
|
+
console.log('read');
|
|
274
|
+
return [4 /*yield*/, cli.read({
|
|
275
|
+
id: id,
|
|
276
|
+
range: 'A1:B4'
|
|
277
|
+
})];
|
|
278
|
+
case 5:
|
|
279
|
+
rres = _c.sent();
|
|
280
|
+
console.log('read res');
|
|
281
|
+
console.log(rres);
|
|
282
|
+
sheet = cli.getSheeOps(id);
|
|
283
|
+
sheet.doBatchUpdate({
|
|
284
|
+
"requests": [
|
|
285
|
+
{
|
|
286
|
+
"updateDimensionProperties": {
|
|
287
|
+
"range": {
|
|
288
|
+
"sheetId": 0,
|
|
289
|
+
"dimension": "COLUMNS",
|
|
290
|
+
"startIndex": 0,
|
|
291
|
+
"endIndex": 1
|
|
292
|
+
},
|
|
293
|
+
"properties": {
|
|
294
|
+
"pixelSize": 100
|
|
295
|
+
},
|
|
296
|
+
"fields": "pixelSize"
|
|
297
|
+
},
|
|
298
|
+
}
|
|
299
|
+
]
|
|
300
|
+
});
|
|
301
|
+
return [4 /*yield*/, sheet.append('A:B', [['c', 'D']])];
|
|
302
|
+
case 6:
|
|
303
|
+
_c.sent();
|
|
304
|
+
_b = (_a = console).log;
|
|
305
|
+
return [4 /*yield*/, sheet.read('A1:B4')];
|
|
306
|
+
case 7:
|
|
307
|
+
_b.apply(_a, [_c.sent()]);
|
|
308
|
+
return [2 /*return*/];
|
|
309
|
+
}
|
|
310
|
+
});
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
exports.test = test;
|
|
314
|
+
//test().catch(err => {
|
|
315
|
+
// console.log(err.response.text);
|
|
316
|
+
//})
|
package/lib/index.d.ts
ADDED
package/lib/index.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getClientByEnv = exports.getClient = exports.getFormData = void 0;
|
|
4
|
+
var googleApi_1 = require("./googleApi");
|
|
5
|
+
Object.defineProperty(exports, "getFormData", { enumerable: true, get: function () { return googleApi_1.getFormData; } });
|
|
6
|
+
Object.defineProperty(exports, "getClient", { enumerable: true, get: function () { return googleApi_1.getClient; } });
|
|
7
|
+
Object.defineProperty(exports, "getClientByEnv", { enumerable: true, get: function () { return googleApi_1.getClientByEnv; } });
|
package/package.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@gzhangx/googleapi",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "google api helper",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"test": "echo \"Error: no test specified\" && exit 1"
|
|
8
|
+
},
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/gzhangx/googleApi.git"
|
|
12
|
+
},
|
|
13
|
+
"author": "",
|
|
14
|
+
"license": "ISC",
|
|
15
|
+
"bugs": {
|
|
16
|
+
"url": "https://github.com/gzhangx/googleApi/issues"
|
|
17
|
+
},
|
|
18
|
+
"homepage": "https://github.com/gzhangx/googleApi#readme",
|
|
19
|
+
"dependencies": {
|
|
20
|
+
"axios": "^0.26.1",
|
|
21
|
+
"follow-redirects": "^1.14.9"
|
|
22
|
+
},
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"@types/node": "^17.0.21",
|
|
25
|
+
"typescript": "^4.6.2"
|
|
26
|
+
}
|
|
27
|
+
}
|
package/pub.bat
ADDED
package/src/googleApi.ts
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
|
|
2
|
+
//rootUrl = 'https://accounts.google.com/o/oauth2/v2/auth';
|
|
3
|
+
//opts = { access_type: 'offline', scope: 'https://www.googleapis.com/auth/spreadsheets', response_type: 'code', client_id: 'client_id', redirect_uri: 'urn:ietf:wg:oauth:2.0:oob' }
|
|
4
|
+
//return rootUrl + '?' + querystring.stringify(opts);
|
|
5
|
+
//'https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fspreadsheets&response_type=code&client_id=client_id&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob'
|
|
6
|
+
|
|
7
|
+
import axios, {Method} from 'axios';
|
|
8
|
+
|
|
9
|
+
export interface IRefresCreds {
|
|
10
|
+
refresh_token: string;
|
|
11
|
+
client_id: string;
|
|
12
|
+
client_secret: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
export function getFormData(obj: { [id: string]: any }): (string|null) {
|
|
17
|
+
if (!obj) return null;
|
|
18
|
+
const keys = Object.keys(obj);
|
|
19
|
+
const data = keys.map(key => {
|
|
20
|
+
let v = obj[key];
|
|
21
|
+
if (typeof v === 'number') v = '' + v;
|
|
22
|
+
return `${key}=${encodeURIComponent(obj[key])}`;
|
|
23
|
+
}).join('&')
|
|
24
|
+
return data;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface IIdRange {
|
|
28
|
+
id: string; range: string;
|
|
29
|
+
}
|
|
30
|
+
type IAppendFunc = (idRng: IIdRange, data: any, opts?: any) => Promise<any>;
|
|
31
|
+
type IReadFunc = (idRng: IIdRange) => Promise<any>;
|
|
32
|
+
export interface IGoogleClient {
|
|
33
|
+
access_token: string;
|
|
34
|
+
expires_on: number;
|
|
35
|
+
token_type: string;
|
|
36
|
+
doBatchUpdate: (id: string, data: any) => Promise<any>;
|
|
37
|
+
append: IAppendFunc;
|
|
38
|
+
read: IReadFunc;
|
|
39
|
+
getSheeOps: (id: string) => {
|
|
40
|
+
doBatchUpdate: (data: any) => Promise<any>;
|
|
41
|
+
append: (range:string, data: any, opts?: any) => Promise<any>;
|
|
42
|
+
read: (range:string)=>Promise<any>;
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function doRefresh(creds: IRefresCreds): Promise<IGoogleClient> {
|
|
47
|
+
const { refresh_token, client_id, client_secret } = creds;
|
|
48
|
+
|
|
49
|
+
const dataStr = getFormData({
|
|
50
|
+
client_secret,
|
|
51
|
+
client_id,
|
|
52
|
+
refresh_token,
|
|
53
|
+
grant_type: 'refresh_token'
|
|
54
|
+
});
|
|
55
|
+
const refreshBody = await axios.post('https://oauth2.googleapis.com/token', dataStr,
|
|
56
|
+
{ headers: { "Content-Type": "application/x-www-form-urlencoded" } }).then(r => {
|
|
57
|
+
return r.data;
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
const {
|
|
61
|
+
access_token, expires_in, token_type
|
|
62
|
+
} = refreshBody;
|
|
63
|
+
const doOp = (op: string, id: string, postFix: string, data?: any) =>
|
|
64
|
+
axios({
|
|
65
|
+
url: `https://sheets.googleapis.com/v4/spreadsheets/${id}${postFix}`,
|
|
66
|
+
headers: {
|
|
67
|
+
"Content-Type": "application/json",
|
|
68
|
+
"Authorization": `Bearer ${access_token}`,
|
|
69
|
+
},
|
|
70
|
+
method:op as Method,
|
|
71
|
+
data,
|
|
72
|
+
}).then(r => {
|
|
73
|
+
return (r.data)
|
|
74
|
+
});
|
|
75
|
+
const doPost = (id:string, postFix:string, data:any) => doOp('post', id, postFix, data);
|
|
76
|
+
const doBatchUpdate = async (id:string, data:any) => doPost(id, ':batchUpdate', data);
|
|
77
|
+
const append: IAppendFunc = async ({ id, range }, data, opts) => {
|
|
78
|
+
if (!opts) {
|
|
79
|
+
opts = {}
|
|
80
|
+
}
|
|
81
|
+
if (!opts.valueInputOption) opts.valueInputOption = 'USER_ENTERED';
|
|
82
|
+
return await doPost(id, `/values/${range}:append?${getFormData(opts)}`, { values: data });
|
|
83
|
+
};
|
|
84
|
+
const read: IReadFunc = async ({ id, range }) => doOp('get', id, `/values/${range}`);
|
|
85
|
+
return {
|
|
86
|
+
access_token,
|
|
87
|
+
expires_on: new Date().getTime() + (expires_in * 1000 - 2000),
|
|
88
|
+
token_type,
|
|
89
|
+
doBatchUpdate,
|
|
90
|
+
append,
|
|
91
|
+
read,
|
|
92
|
+
getSheeOps: id => {
|
|
93
|
+
return {
|
|
94
|
+
doBatchUpdate: data => doBatchUpdate(id, data),
|
|
95
|
+
append: (range, data, ops) => append({ id, range }, data, ops),
|
|
96
|
+
read: range => read({ id, range }),
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const clients = {} as {
|
|
103
|
+
[name: string]: IGoogleClient;
|
|
104
|
+
};
|
|
105
|
+
export async function getClient(creds: IRefresCreds) {
|
|
106
|
+
const name = creds.client_id;
|
|
107
|
+
let client = clients[name];
|
|
108
|
+
const now = new Date().getTime();
|
|
109
|
+
if (!client || client.expires_on <= now) {
|
|
110
|
+
client = await doRefresh(creds);
|
|
111
|
+
if (!client) return null;
|
|
112
|
+
clients[name] = client;
|
|
113
|
+
}
|
|
114
|
+
return client;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export async function getClientByEnv(envName: string) {
|
|
118
|
+
const creds: IRefresCreds = {
|
|
119
|
+
client_id: process.env[`google.${envName}.client_id`] as string,
|
|
120
|
+
client_secret: process.env[`google.${envName}.client_secret`] as string,
|
|
121
|
+
refresh_token: process.env[`google.${envName}.refresh_token`] as string,
|
|
122
|
+
};
|
|
123
|
+
return getClient(creds);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export async function test(d:boolean) {
|
|
127
|
+
const cli = await getClientByEnv('gzprem');
|
|
128
|
+
|
|
129
|
+
if (!cli) return console.log('failed to get client');
|
|
130
|
+
const id = '1MO27odjCsxk6MWL0DygubU53hrtt3OB8SEnqjpUHJ-U';
|
|
131
|
+
if (d) return;
|
|
132
|
+
console.log('do batch update');
|
|
133
|
+
await cli.doBatchUpdate(id, {
|
|
134
|
+
"requests": [
|
|
135
|
+
{
|
|
136
|
+
"updateDimensionProperties": {
|
|
137
|
+
"range": {
|
|
138
|
+
"sheetId": 0,
|
|
139
|
+
"dimension": "COLUMNS",
|
|
140
|
+
"startIndex": 0,
|
|
141
|
+
"endIndex": 1
|
|
142
|
+
},
|
|
143
|
+
"properties": {
|
|
144
|
+
"pixelSize": 160
|
|
145
|
+
},
|
|
146
|
+
"fields": "pixelSize"
|
|
147
|
+
},
|
|
148
|
+
|
|
149
|
+
}
|
|
150
|
+
]
|
|
151
|
+
})
|
|
152
|
+
console.log('do batch update 2');
|
|
153
|
+
const upres = await cli.doBatchUpdate(id, {
|
|
154
|
+
"requests": [
|
|
155
|
+
{
|
|
156
|
+
|
|
157
|
+
"updateCells": {
|
|
158
|
+
"fields": "*",
|
|
159
|
+
"range": {
|
|
160
|
+
"sheetId": 0,
|
|
161
|
+
"startColumnIndex": 0,
|
|
162
|
+
"endColumnIndex": 10,
|
|
163
|
+
"startRowIndex": 0,
|
|
164
|
+
"endRowIndex": 10
|
|
165
|
+
},
|
|
166
|
+
"rows": [
|
|
167
|
+
{
|
|
168
|
+
"values": [
|
|
169
|
+
{
|
|
170
|
+
"userEnteredFormat": {
|
|
171
|
+
"backgroundColor": {
|
|
172
|
+
"blue": 10,
|
|
173
|
+
"green": 10,
|
|
174
|
+
"red": 255
|
|
175
|
+
},
|
|
176
|
+
"borders": {
|
|
177
|
+
"bottom": {
|
|
178
|
+
"style": "SOLID",
|
|
179
|
+
"width": 8,
|
|
180
|
+
"color": {
|
|
181
|
+
"blue": 0,
|
|
182
|
+
"green": 255,
|
|
183
|
+
"red": 0
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
},
|
|
188
|
+
"userEnteredValue": { "stringValue": "strstsdfasdf" }
|
|
189
|
+
},
|
|
190
|
+
{
|
|
191
|
+
"userEnteredValue": { "stringValue": "col1" }
|
|
192
|
+
}
|
|
193
|
+
]
|
|
194
|
+
}
|
|
195
|
+
]
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
]
|
|
199
|
+
});
|
|
200
|
+
console.log(upres);
|
|
201
|
+
|
|
202
|
+
console.log('append 1');
|
|
203
|
+
const appres = await cli.append({
|
|
204
|
+
id,
|
|
205
|
+
range: `'Sheet1'!A1:B2`
|
|
206
|
+
}, [
|
|
207
|
+
['aaa', 'bbb1']
|
|
208
|
+
])
|
|
209
|
+
console.log('append res');
|
|
210
|
+
console.log(appres);
|
|
211
|
+
|
|
212
|
+
console.log('read');
|
|
213
|
+
const rres = await cli.read({
|
|
214
|
+
id,
|
|
215
|
+
range: 'A1:B4'
|
|
216
|
+
});
|
|
217
|
+
console.log('read res');
|
|
218
|
+
console.log(rres);
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
const sheet = cli.getSheeOps(id);
|
|
223
|
+
sheet.doBatchUpdate({
|
|
224
|
+
"requests": [
|
|
225
|
+
{
|
|
226
|
+
"updateDimensionProperties": {
|
|
227
|
+
"range": {
|
|
228
|
+
"sheetId": 0,
|
|
229
|
+
"dimension": "COLUMNS",
|
|
230
|
+
"startIndex": 0,
|
|
231
|
+
"endIndex": 1
|
|
232
|
+
},
|
|
233
|
+
"properties": {
|
|
234
|
+
"pixelSize": 100
|
|
235
|
+
},
|
|
236
|
+
"fields": "pixelSize"
|
|
237
|
+
},
|
|
238
|
+
|
|
239
|
+
}
|
|
240
|
+
]
|
|
241
|
+
})
|
|
242
|
+
await sheet.append('A:B', [['c', 'D']]);
|
|
243
|
+
console.log(await sheet.read('A1:B4'));
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
//test().catch(err => {
|
|
247
|
+
// console.log(err.response.text);
|
|
248
|
+
//})
|
|
249
|
+
|
package/src/index.ts
ADDED
package/test.bat
ADDED
package/tsconfig.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"incremental": true, /* Enable incremental compilation */
|
|
4
|
+
"target": "es5", /* Specify ECMAScript target version: */
|
|
5
|
+
"module": "commonjs", /* 'none', 'commonjs', 'amd', 'system', etc */
|
|
6
|
+
"declaration": true, /* Concatenate & emit output to single file.*/
|
|
7
|
+
"outDir": "lib", /* Redirect output to the directory. */
|
|
8
|
+
"esModuleInterop": true, /* Enables intero between CommonJS and ES */
|
|
9
|
+
"skipLibCheck": true, /* Skip type checking of declaration files. */
|
|
10
|
+
"forceConsistentCasingInFileNames": true /* Disallow inconsistently */
|
|
11
|
+
},
|
|
12
|
+
"include": [
|
|
13
|
+
"src"
|
|
14
|
+
]
|
|
15
|
+
}
|