UNPKG

3.61 kBJavaScriptView Raw
1'use strict';
2
3const path = require('path');
4const glob = require('glob');
5const fs = require('fs-extra');
6
7const JSONSchemaSequelizer = require('../lib');
8
9module.exports = (conn, config) => {
10 const _cwd = process.cwd();
11 const _umzug = JSONSchemaSequelizer.migrate(conn.sequelize);
12
13 const _allowed = typeof config.options.only === 'string'
14 ? String(config.options.only).split(',')
15 : [];
16
17 /* istanbul ignore else */
18 if (Array.isArray(config.options.only)) {
19 Array.prototype.push.apply(_allowed, config.options.only);
20 }
21
22 const _models = Object.keys(conn.models)
23 .filter(x => (_allowed.length ? _allowed.indexOf(x) !== -1 : true))
24 .map(x => conn.models[x]);
25
26 const _logger = config.logger || {};
27
28 _logger.error = _logger.error || console.error.bind(console);
29 _logger.message = _logger.message || console.log.bind(console);
30
31 function load() {
32 /* istanbul ignore else */
33 if (typeof config.options.load !== 'string') {
34 throw new Error(`Invalid directory to --load, given '${config.options.load}'`);
35 }
36
37 const src = path.resolve(_cwd, config.options.load);
38 const after = path.resolve(path.dirname(src), config.options.after || 'after.js');
39 const before = path.resolve(path.dirname(src), config.options.before || 'after.js');
40
41 return Promise.resolve()
42 .then(() => _umzug.run(before))
43 .then(() => Promise.all(_models.filter(x => !x.virtual)
44 .map(x => {
45 const file = glob.sync(`**/${x.name}.json`, { cwd: src })[0];
46
47 /* istanbul ignore else */
48 if (!file) {
49 return _logger.message(`${x.name} was skipped`);
50 }
51
52 return x
53 .bulkCreate(fs.readJsonSync(path.join(src, file)))
54 .then(() => {
55 _logger.message(`${x.name} was loaded`);
56 });
57 })))
58 .then(() => _umzug.run(after));
59 }
60
61 function save() {
62 const fulldate = [
63 new Date().getFullYear(),
64 `0${new Date().getMonth() + 1}`.substr(-2),
65 `0${new Date().getDate() + 1}`.substr(-2),
66 ].join('');
67
68 const hourtime = [
69 `0${new Date().getHours()}`.substr(-2),
70 `0${new Date().getMinutes()}`.substr(-2),
71 `0${new Date().getSeconds()}`.substr(-2),
72 '.',
73 `000${new Date().getMilliseconds()}`.substr(-3),
74 ].join('');
75
76 return Promise.all(_models.filter(x => !x.virtual)
77 .map(x => x
78 .findAll({
79 order: [[x.primaryKeyAttribute, 'ASC']],
80 // FIXME: export nested-data instead?
81 raw: true,
82 })
83 .then(data => ({ data, model: x }))))
84 .then(results => {
85 const _buffer = [];
86
87 results.forEach(result => {
88 /* istanbul ignore else */
89 if (config.options.save) {
90 /* istanbul ignore else */
91 if (typeof config.options.save !== 'string') {
92 throw new Error(`Invalid directory to --save, given '${config.options.save}'`);
93 }
94
95 const file = path.join(_cwd, config.options.save, `${fulldate}${hourtime}`, `${result.model.name}.json`);
96
97 fs.outputJsonSync(file, result.data, { spaces: 2 });
98
99 return _logger.message(`write ${path.relative(_cwd, file)}`);
100 }
101
102 _buffer.push(`\r\n--- BEGIN ${result.model.name} ---\n${JSON.stringify(result.data, null, 2)}\n--- END ${result.model.name} ---\n`);
103 });
104
105 /* istanbul ignore else */
106 if (_buffer.length) {
107 _logger.message(_buffer.join(''));
108 }
109 });
110 }
111
112 return Promise.resolve()
113 .then(() => (config.options.load ? load() : save()));
114};