-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
64 lines (56 loc) · 1.66 KB
/
index.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
const yaml = require("js-yaml");
const fs = require("fs");
const { google } = require("googleapis");
const { authorize } = require("./utils/google_auth");
const config = require('./config/config');
const {
SPREAD_SHEET_ID,
SPECIFIED_RANGE,
LEFT_COLUMN_IS_KEY,
CREDENTIAL_PATH,
} = config
// Load client secrets from a local file.
fs.readFile(CREDENTIAL_PATH, (err, content) => {
if (err) return console.log("Error loading client secret file:", err);
// Authorize a client with credentials, then call the Google Sheets API.
authorize(JSON.parse(content), convertSheetData2Yaml);
});
const writeJson2Yaml = rows => {
const formatedData = {};
rows.map(row => {
if (LEFT_COLUMN_IS_KEY) {
formatedData[row[0]] = row[1];
} else {
formatedData[row[1]] = row[0];
}
// console.log('formatedData: ', formatedData);
});
// See more dump params at:
// https://github.com/nodeca/js-yaml#safedump-object---options-
const res = yaml.safeDump(formatedData, {
styles: {
"!!null": "canonical" // dump null as ~
},
sortKeys: true // sort object keys
});
fs.writeFileSync("./tmp/result.yaml", res);
console.log("Data has been written into tmp/result.yaml");
};
function convertSheetData2Yaml(auth) {
const sheets = google.sheets({ version: "v4", auth });
sheets.spreadsheets.values.get(
{
spreadsheetId: SPREAD_SHEET_ID,
range: SPECIFIED_RANGE
},
(err, res) => {
if (err) return console.log("The API returned an error: " + err);
const rows = res.data.values;
if (rows.length) {
writeJson2Yaml(rows);
} else {
console.log("No data found.");
}
}
);
}