-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
executable file
·535 lines (416 loc) · 11.4 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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
#!/usr/bin/env node
/**
* bigC2elastic
* index.js
**/
'use strict';
/**
*
* Dependencies and constants
*
**/
const chalk = require('chalk');
const {
bigC: { listCategories, fetchBrands, fetchProducts },
elastic: { fetchDocuments, deleteDocuments, postDocuments },
} = require('./lib/services');
const {
bigC: { partitionAndFormat },
elastic: {
formatForDeletion,
mapBrands,
parseResponse,
partitionAndFormatProducts,
},
} = require('./lib/utils');
const { log, time, timeEnd } = console;
require('dotenv').config();
const fs = require('fs');
const inquirer = require('inquirer');
const ui = new inquirer.ui.BottomBar();
const [, , ...flags] = process.argv;
const ONLY_PRODUCTS = flags.indexOf('--products-only') !== -1;
const DROP = flags.indexOf('--drop') !== -1;
const NO_BRANDS = flags.indexOf('--no-brands') !== -1;
const NO_CATEGORIES = flags.indexOf('--no-categories') !== -1;
let INIT = flags.indexOf('--init') !== -1;
const { env: e } = process;
if (
!e.BIGC_STORE_HASH ||
!e.BIGC_AUTH_TOKEN ||
!e.ELASTIC_ENDPOINT ||
!e.ELASTIC_ENGINE ||
!e.ELASTIC_BEARER_TOKEN
)
INIT = true;
/**
*
* MAIN
*
**/
async function run() {
/**
*
* Labels/housekeeping
*
**/
const processLabel = 'Elasticsearch Sync';
let functionLabel;
time(processLabel);
log(chalk.blue('Starting sync...'));
/**
*
* If --drop, fetch and drop docs in batches of 100
*
**/
if (DROP) {
const iterator = fetchDocuments();
let ids = [];
functionLabel = 'Dropped existing documents';
time(functionLabel);
log(chalk.magenta('Drop requested...'));
let docPage = 1;
for await (const page of iterator) {
log(chalk.magenta(`Fetching page ${docPage}`));
for (const doc of page) {
const { id, name } = doc;
ids.push({ id, name });
}
docPage++;
}
while (ids.length > 0) {
const hundredDocs = ids.splice(0, 100);
log(chalk.magenta('Dropping in batches of 100'));
const { data: dropResponse } = await deleteDocuments(
formatForDeletion(hundredDocs)
);
const [runner, result, ...rest] = parseResponse(
dropResponse,
hundredDocs
);
log(chalk.magenta(runner));
log(chalk.green(result));
for (const exception of rest) {
log(chalk.yellow(exception));
}
}
timeEnd(functionLabel);
}
/**
*
* Fetch categories to provide cateogry names to product docs.
* Unless --no-categories or --products-only, push category docs to
* elasticsearch in batches of 100
*
**/
functionLabel = 'Fetch categories';
time(functionLabel);
log(chalk.magenta('Fetching categories from BigC...'));
const categoryResponse = await listCategories();
timeEnd(functionLabel);
if (!ONLY_PRODUCTS && !NO_CATEGORIES) {
let [visibleCategories, hiddenCategories] =
partitionAndFormat(categoryResponse);
log(chalk.magenta('Deleting hidden categories...'));
functionLabel = 'Deleted hidden categories';
time(functionLabel);
const { data: deleteCategoryResponse } = await deleteDocuments(
formatForDeletion(hiddenCategories)
);
const [runner, result, ...rest] = parseResponse(
deleteCategoryResponse,
hiddenCategories
);
log(chalk.magenta(runner));
log(chalk.green(result));
for (const unDeleted of rest) {
log(chalk.yellow(unDeleted));
}
timeEnd(functionLabel);
functionLabel = 'Updated categories';
time(functionLabel);
log(chalk.magenta('Updating categories'));
while (visibleCategories.length > 0) {
if (visibleCategories.length > 100) {
const firstHundredCategories = visibleCategories.splice(0, 100);
const { data: postedCategories = [] } = await postDocuments(
firstHundredCategories
);
const [categoryRunner, updatedResult, ...rest] = parseResponse(
postedCategories,
firstHundredCategories
);
log(chalk.magenta(categoryRunner));
log(chalk.green(updatedResult));
for (const remaining of rest) {
log(chalk.yellow(remaining));
}
} else {
const { data: postedCategories = [] } = await postDocuments(
visibleCategories
);
const [categoryRunner, updatedResult, ...rest] = parseResponse(
postedCategories,
visibleCategories
);
log(chalk.magenta(categoryRunner));
log(chalk.green(updatedResult));
for (const remaining of rest) {
log(chalk.yellow(remaining));
}
visibleCategories.length = 0;
}
}
timeEnd(functionLabel);
}
/**
*
* Fetch brands to provide brand names to product docs.
* Unless --no-brands or --products-only, push resulting brand docs up to
* elasticsearch in batches of 100.
*
**/
functionLabel = 'Fetch brands';
time(functionLabel);
log(chalk.magenta('Mapping brands'));
let brandPages = 0;
const brandIterator = fetchBrands();
const brandArray = [];
for await (const brandPage of brandIterator) {
brandPages++;
log(chalk.blue(`Page: ${brandPages}`));
brandArray.push(...brandPage);
}
const brandKey = mapBrands(brandArray);
timeEnd(functionLabel);
if (!ONLY_PRODUCTS && !NO_BRANDS) {
functionLabel = 'Updating brands';
time(functionLabel);
let formattedBrands = brandKey.map((brand) => {
const formatted = { ...brand };
formatted.id = 'bc2eB' + brand.id;
return formatted;
});
while (formattedBrands.length > 0) {
if (formattedBrands.length > 100) {
const firstHundredBrands = formattedBrands.splice(0, 100);
const { data: postedBrands = [] } = await postDocuments(
firstHundredBrands
);
const [brandRunner, updatedResult, ...rest] = parseResponse(
postedBrands,
firstHundredBrands
);
log(chalk.magenta(brandRunner));
log(chalk.green(updatedResult));
for (const remaining of rest) {
log(chalk.yellow(remaining));
}
} else {
const { data: postedBrands = [] } = await postDocuments(
formattedBrands
);
const [brandRunner, updatedResult, ...rest] = parseResponse(
postedBrands,
formattedBrands
);
log(chalk.magenta(brandRunner));
log(chalk.green(updatedResult));
for (const remaining of rest) {
log(chalk.yellow(remaining));
}
formattedBrands.length = 0;
}
}
timeEnd(functionLabel);
}
/**
*
* Fetch products from BigC, one page at a time.
* Label brand and categories and push resulting docs back up to elasticsearch
*
**/
log(chalk.magenta('Fetching product pages'));
functionLabel = 'Fetched product pages';
let totalPages = 0;
const iterator = fetchProducts();
for await (const page of iterator) {
totalPages++;
log(chalk.blue(`Page: ${totalPages}`));
const [toUpdate, toDelete] = partitionAndFormatProducts(
page,
categoryResponse,
brandKey
);
let localLabel = 'Deleted hidden products';
log(chalk.magenta('Deleting hidden products...'));
time(localLabel);
const { data: deleteProductsResponse = [] } = await deleteDocuments(
formatForDeletion(toDelete)
);
const [deletedRunner, deletedResult, ...deletedRest] = parseResponse(
deleteProductsResponse,
toDelete
);
log(chalk.magenta(deletedRunner));
log(chalk.green(deletedResult));
for (const unDeleted of deletedRest) {
log(chalk.yellow(unDeleted));
}
timeEnd(localLabel);
localLabel = 'Updated products';
log(chalk.magenta('Updating products'));
time(localLabel);
const { data: postedDocuments = [] } = await postDocuments(toUpdate);
const [updatedRunner, updatedResult, ...updatedRest] = parseResponse(
postedDocuments,
toUpdate
);
log(chalk.magenta(updatedRunner));
log(chalk.green(updatedResult));
for (const remaining of updatedRest) {
log(chalk.yellow(remaining));
}
timeEnd(localLabel);
}
/**
*
* Cleanup
*
**/
log(chalk.blue('Finished'));
timeEnd(processLabel);
process.exit(0);
}
/**
*
* Inquirer .env setup for --init
*
**/
function formatEnv(answers) {
const env = ['# BIG C VARIABLES'];
env.push(`BIGC_STORE_HASH=${answers.storeHash}`);
env.push(`BIGC_AUTH_TOKEN=${answers.bigCAuth}`);
env.push('# ELASTIC SEARCH VARIABLES');
env.push(`ELASTIC_ENDPOINT=${answers.elasticEndPoint}`);
env.push(`ELASTIC_ENGINE=${answers.elasticEngine}`);
env.push(`ELASTIC_BEARER_TOKEN=${answers.elasticToken}`);
return env.join('\n');
}
/**
*
* check for .env and begin init if keys are missing
*
**/
if (INIT) {
const environmentQuestions = [
{
type: 'input',
name: 'storeHash',
message: 'What is your BigCommerce store hash? (ie: 10lp3d)',
validate: (answer) => {
if (answer.length !== 6) {
log('\nThat does not look right');
return false;
}
return true;
},
},
{
type: 'input',
name: 'bigCAuth',
message:
'What is your BigCommerce API auth token? (31 alphanumeric chars)',
validate: (answer) => {
if (!answer.length) {
log('\nThat does not look right');
return false;
}
return true;
},
},
{
type: 'input',
name: 'elasticEndPoint',
message:
'What is the endpoint of your elasticsearch db? (ie: https://' +
'foo.com)',
validate: (answer) => {
const re = /^https?:\/\/.*/;
if (!answer.match(re)) {
log('\nThat does not look right');
return false;
}
return true;
},
},
{
type: 'input',
name: 'elasticEngine',
message:
'What is the name of your elasticsearch engine? (ie: ' +
'foo-search-engine)',
validate: (answer) => {
if (!answer.length) {
log('\nThat does not look right');
return false;
}
return true;
},
},
{
type: 'input',
name: 'elasticToken',
message: 'Please provide your elasticsearch bearer token',
validate: (answer) => {
if (!answer.length) {
log('\nThat does not look right');
return false;
}
return true;
},
},
{
type: 'confirm',
name: 'confirm',
message: (answers) => {
log('ENV variables:\n');
log(formatEnv(answers));
log('\nWrite ENV variabled to .env?');
},
},
];
ui.log.write('bigc2elastic init: setting environmental variables');
inquirer
.prompt(environmentQuestions)
.then((answers) => {
if (!answers.confirm) {
log('Discarding ENV variables.');
return;
}
const env = formatEnv(answers);
fs.writeFile('./.env', env, (err) => {
if (err) {
log('Problems writing to filesystem...');
console.error(err);
return;
}
log('ENV created!');
});
})
.catch((error) => {
if (error.isTtyError) {
// Prompt can't be rendered in the current environment
log('This terminal is not playing nice');
} else {
log(error);
}
});
} else {
try {
run();
} catch (err) {
console.error(err);
process.exit(1);
}
}