-
Notifications
You must be signed in to change notification settings - Fork 0
/
import.js
111 lines (96 loc) · 2.78 KB
/
import.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
'use strict';
// Dependencies
const firestoreService = require('firestore-export-import');
const serviceAccount = require('./serviceAccount.json');
const excelToJson = require('convert-excel-to-json');
const inquirer = require('inquirer')
const inquirerFileTreeSelection = require('inquirer-file-tree-selection-prompt')
const path = require('path');
const chalk = require('chalk');
const fs = require('fs');
const selectFile = async () => {
// Select file to import
inquirer.registerPrompt('file-tree-selection', inquirerFileTreeSelection)
var answers = await inquirer
.prompt([
{
type: 'file-tree-selection',
name: 'file',
message: 'Select the file you would like to import:',
pageSize: 5,
root: './data/',
validate: (item) => {
const type = path.extname(item);
if (type != ".xlsx" && type != ".json") {
return 'Only Excel and JSON files are supported. Please select another file.'
}
return true;
},
onlyShowValid: true,
}
]);
return answers.file;
}
const convertFile = async (file) => {
if (path.extname(file) == '.xlsx') {
var answers = await inquirer
.prompt([
{
type: 'confirm',
name: 'convert',
message: 'Proceed to convert ' + file + ' to JSON?',
}
]);
if (answers.convert) {
// Convert Excel to JSON
console.log('Converting...');
const result = excelToJson({
sourceFile: file,
header:{
rows: 1
},
columnToKey: {
'*': '{{columnHeader}}'
}
});
// TODO: Prompt user to select file name
var newFile = './data/data.json';
if (fs.existsSync(newFile)) {
answers = await inquirer
.prompt([
{
type: 'confirm',
name: 'overwrite',
message: 'File ' + newFile + ' already exists. Overwrite?',
}
]);
if (!answers.overwrite) {
console.log('Import cancelled.');
process.exit(0);
}
}
fs.writeFileSync(newFile, JSON.stringify(result), 'utf8');
console.log('File ' + newFile + ' created.');
return newFile;
} else {
console.log('Import cancelled.');
process.exit(0);
}
}
return file;
}
// JSON To Firestore
const jsonToFirestore = async (file) => {
console.log('Initialzing Firebase...');
await firestoreService.initializeApp(serviceAccount);
console.log('Firebase initialized.');
console.log('Uploading file...')
await firestoreService.restore(file);
console.log('Upload success.');
};
const main = async () => {
var file = await selectFile();
var newFile = await convertFile(file);
jsonToFirestore(newFile);
}
main()