This repository has been archived by the owner on Jul 22, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
sync.js
66 lines (57 loc) · 1.44 KB
/
sync.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
'use strict';
var _ = require('lodash');
var Promise = require('bluebird');
var Resolver = require('./resolver');
/**
* Module interface.
*/
module.exports = sync;
/**
* Synchronize given schemas with database. If it exists, it calls `postBuild` afterwards
*
* @param {[Schemas]} schemas
* @return {Promise}
*/
function sync(schemas) {
var resolver = new Resolver(schemas);
// Reduce force sequential execution.
return Promise.resolve(Promise.reduce(resolver.resolve(), syncSchema.bind(this), []))
.tap(function () {
var knex = this.knex;
return Promise.map(schemas || [], function(schema) {
return (schema.postBuild || _.noop)(knex);
});
}.bind(this));
}
/**
* Synchronize given schema with database.
*
* @param {[Schema]} result - reduce accumulator
* @param {Schema} schema
* @return {Promise}
*/
function syncSchema(result, schema) {
var knex = this.knex;
return knex.schema.hasTable(schema.tableName)
.then(function (exists) {
if (exists) return result;
return knex.schema.createTable(schema.tableName, defineSchemaTable(schema))
.then(function () {
return result.concat([schema]);
});
});
}
/**
* Define default properties on the given schema.
*
* @param {Schema} schema
* @return {Function}
*/
function defineSchemaTable(schema) {
return function (table) {
table.engine('InnoDB');
table.timestamps();
table.charset('utf8');
(schema.build || _.noop)(table);
};
}