This repository has been archived by the owner on Sep 6, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
createGapi.js
82 lines (81 loc) · 2.29 KB
/
createGapi.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
module.exports = function({
google,
googleAuth,
sheetId,
secrets,
adapter,
store,
}) {
const SCOPES = ['https://www.googleapis.com/auth/spreadsheets'];
return {
getClient: function getClient(username) {
const auth = new googleAuth.GoogleAuth();
const oauth2Client = new auth.OAuth2Client(
secrets.installed.client_id,
secrets.installed.client_secret,
secrets.installed.redirect_uris[0],
);
return store.find(username)
.then(credentials => {
oauth2Client.credentials = credentials
return Promise.resolve(oauth2Client);
})
.catch(e => Promise.resolve(oauth2Client));
},
getLink: function(oauth2Client) {
return oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
},
authorize: function(oauth2Client, username, code) {
return new Promise((resolve, reject)=> {
if (Object.keys(oauth2Client.credentials).length !== 0) {
resolve('already');
} else {
oauth2Client.getToken(code, function(err, token) {
if (err) {
return reject(err);
}
oauth2Client.credentials = token;
resolve(store.save(username, token));
});
}
});
},
append: function(oauth2Client, data) {
return new Promise((resolve, reject) => {
const sheets = google.sheets('v4');
sheets.spreadsheets.values.append({
auth: oauth2Client,
spreadsheetId: sheetId,
range: adapter.insertRange(),
valueInputOption: 'USER_ENTERED',
resource: {
values: [adapter.dataToRow(data)]
}
}, function(err, response) {
if (err) {
return reject(err);
}
resolve('OK');
})
});
},
categories: function(oauth2Client) {
return new Promise((resolve, reject) => {
const sheets = google.sheets('v4');
sheets.spreadsheets.values.get({
auth: oauth2Client,
spreadsheetId: sheetId,
range: adapter.categoriesRange(),
}, function(err, response) {
if (err) {
return reject(err);
}
resolve(response.values);
});
});
},
};
};