This repository has been archived by the owner on Oct 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
218 lines (180 loc) · 5.68 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
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
require('dotenv').config();
const fs = require('fs');
const {sep} = require('path');
const ora = require('ora');
const chalk = require('chalk');
const PromiseQueue = require('promise-queue');
const got = require('got');
const get = require('lodash.get');
class Seeder {
constructor(logHandler, showSpinner) {
this.log = logHandler;
this.showSpinner = showSpinner
}
async run(path = process.cwd()) {
// Get a list of all seed files in the provided directory
const entries = Object.entries(this.parsePath(path.replace(new RegExp(`${sep}$`), '')));
if (entries.length === 0) {
return this.error('The given path must be a .json file or a directory containing at least one valid .json file');
}
// Make categories run first and assets run last
entries.sort(([a], [b]) => {
if (a === 'assets' || b === 'categories') {
return 1;
}
if (b === 'assets' || a === 'categories') {
return -1;
}
return 0;
});
if (this.showSpinner) {
this.spinner = ora({
text: 'Seeding. This may take some time...',
stream: process.stdout,
}).start();
}
const typeCounts = {};
const queuedPromises = [];
const responses = {};
const queue = new PromiseQueue(1, Infinity);
entries.forEach(([endpoint, data]) => {
(Array.isArray(data) ? data : [data]).forEach((datum, index) => {
const {link, ...rest} = datum;
queuedPromises.push(queue.add(() => {
if (this.showSpinner) {
this.spinner.text = `Seeding ${chalk.dim(endpoint)} #${index}. This may take some time...`;
}
// Replace category placeholders with actual category IDs when creating products
if (endpoint === 'products' && rest.product.category_id) {
rest.categories = [{ id: get(responses, rest.product.category_id) }];
rest.product.category_id = undefined;
}
return this.post(`/v1/${endpoint}`, rest)
.then(response => {
if (Object.hasOwnProperty.call(typeCounts, endpoint)) {
typeCounts[endpoint]++;
} else {
responses[endpoint] = [];
typeCounts[endpoint] = 1;
}
responses[endpoint].push(JSON.parse(response.body))
})
.catch(this.apiError);
}
));
if (endpoint === 'assets' && link) {
queuedPromises.push(queue.add(() => {
const assetId = responses.assets[index].id;
const productId = get(responses, link);
return this.post(`/v1/products/${productId}/assets`, {
assets: [{id: assetId}]
}).catch(this.apiError);
}))
}
});
});
await Promise.all(queuedPromises);
const report = Object.entries(typeCounts);
if (report.length === 0) {
if (this.showSpinner) {
this.spinner.fail('Could not seed any of the provided data');
}
return
}
if (this.showSpinner) {
this.spinner.succeed('Completed seeding');
}
this.log('Added:');
report.forEach(([endpoint, count]) => {
this.log(` ${chalk.bold(count)} ${endpoint}`);
})
}
apiError = (error) => {
this.error(`Failed seeding - ${error.message}`);
}
parsePath(path) {
let stat;
try {
stat = fs.statSync(path);
} catch (error) {
return this.error(`Could not access given path: ${chalk.dim(path)}`);
}
let additionalErrorInfo = '';
try {
if (stat.isDirectory()) {
return this.parseDirectory(path);
}
if (stat.isFile()) {
return this.parseFile(path);
}
} catch (error) {
if (error.name === 'SyntaxError') {
additionalErrorInfo = `JSON failed to compile with error: ${chalk.dim(error.message)}.`;
}
}
return this.error(`Could not parse the given path: ${chalk.dim(path)}. ${additionalErrorInfo}`);
}
parseDirectory(directory) {
const files = fs.readdirSync(directory);
const result = {};
for (const file of files) {
// Ignore dotfiles
if (file.startsWith('.') || !file.endsWith('.json')) {
continue;
}
Object.entries(this.parsePath(directory + sep + file)).forEach(([key, value]) => {
if (Object.hasOwnProperty.call(result, key)) {
result[key].push(...value);
} else {
result[key] = value;
}
});
}
return result;
}
parseFile(file) {
if (file.match(/package(-lock)?\.json$/)) {
return {};
}
const contents = JSON.parse(fs.readFileSync(file));
if (Array.isArray(contents)) {
const lastSeperator = file.lastIndexOf(sep);
const endpoint = file.substring(lastSeperator > 0 ? lastSeperator + 1 : 0, file.length - 5);
return {
[endpoint]: contents,
};
}
return contents;
}
post(endpoint, payload) {
const url = process.env.CHEC_API_URL || 'api.chec.io';
const key = process.env.CHEC_SECRET_KEY;
if (!url || !key) {
return this.error(`Required .env keys "${chalk.bold('CHEC_API_URL')}" and/or ${chalk.bold('CHEC_SECRET_KEY')} are missing`);
}
const headers = {
'content-type': 'application/json',
'x-authorization': key,
};
return got(`${url}${endpoint}`, {
method: 'post',
body: JSON.stringify(payload),
headers,
retry: {
retries: 0,
},
});
}
error(log) {
if (this.showSpinner) {
this.spinner.stop();
}
throw new Error(log)
}
}
module.exports = {
seed(path, logHandler = () => {}, spinner = false) {
return new Seeder(logHandler, spinner).run(path);
},
Seeder,
}