-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
78 lines (68 loc) · 1.93 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
const _ = require('lodash')
const knex = require('knex')
const DatastoreTrailpack = require('trailpack/datastore')
/**
* Knex integration for Trails. Allows knex to read its configration from the
* trails datastore config, and auto-migrate on startup.
*/
module.exports = class KnexTrailpack extends DatastoreTrailpack {
/**
* Ensure that this trailpack supports the configured migration
*/
validate () {
/*
if (!_.includes([ 'none', 'drop', 'create' ], this.app.config.database.models.migrate)) {
throw new Error('Migrate must be configured to either "create" or "drop"')
}
*/
}
configure () {
this.app.config.set('stores.orm', 'knex')
}
/**
* Initialize knex connections, and perform migrations.
*/
async initialize () {
super.initialize()
this.stores = _.mapValues(this.app.config.stores, (store, storeName) => {
return {
knex: knex(Object.assign({ }, store)),
models: _.pickBy(this.app.models, { store: storeName }),
migrate: store.migrate
}
})
return this.migrate()
}
/**
* Close all database connections
*/
async unload () {
return Promise.all(
_.map(this.stores, store => store.knex.destroy())
)
}
constructor (app) {
super(app, {
config: require('./config'),
api: require('./api'),
pkg: require('./package')
})
}
/**
* Migrate schema according to the database configuration
*/
migrate () {
const SchemaMigrationService = this.app.services.SchemaMigrationService
return Promise.all(
_.map(this.stores, (store, storeName) => {
if (store.migrate === 'drop') {
return SchemaMigrationService.drop(store.knex, this.app.models)
.then(result => SchemaMigrationService.create(store.knex, this.app.models))
}
else {
return SchemaMigrationService[store.migrate](store.knex, this.app.models)
}
})
)
}
}