Skip to content
Open

V3 #36

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
language: node_js
node_js:
- '4'
- stable
- '8'
- '9'

services: mongodb

Expand Down
3 changes: 0 additions & 3 deletions api/services/FootprintService.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
'use strict'

const _ = require('lodash')
const Service = require('trails/service')

/**
* Trails Service that maps abstract ORM methods to their respective Waterine
Expand Down
16 changes: 9 additions & 7 deletions api/services/SchemaMigrationService.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
'use strict'

const _ = require('lodash')
const Service = require('trails/service')

/**
* @module SchemaMigrationService
* @description Schema Migrations
Expand All @@ -16,9 +11,10 @@ module.exports = class SchemaMigrationService extends Service {
*/
drop (connection) {
return Promise.all(
_.map(connection.collections, collection => {
Object.values(connection.collections).map(collection => {
return new Promise((resolve, reject) => {
collection.drop((err) => {
collection.drop(err => {
if (err) return reject()
resolve()
})
})
Expand All @@ -31,4 +27,10 @@ module.exports = class SchemaMigrationService extends Service {
alter (connection) {
throw new Error('trailpack-mongoose does not currently support migrate=alter')
}

/**
* Do not perform any migrations.
*/
none () {
}
}
73 changes: 34 additions & 39 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
'use strict'

const _ = require('lodash')
const mongoose = require('mongoose')
const DatastoreTrailpack = require('trailpack-datastore')
const DatastoreTrailpack = require('trailpack/datastore')
const lib = require('./lib')

/**
Expand All @@ -15,16 +12,13 @@ module.exports = class MongooseTrailpack 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"')
}
}

/**
* Create default configuration
*/
configure () {
this.app.config.database.orm = 'mongoose'
this.app.config.set('stores.orm', 'mongoose')

this.mongoose = mongoose
}
Expand All @@ -43,20 +37,21 @@ module.exports = class MongooseTrailpack extends DatastoreTrailpack {

this.orm = this.orm || {}
// Need to pick only mongoose stores
const stores = lib.Transformer.pickStores(this.app.config.database.stores)
const stores = lib.Transformer.pickStores(this.app.config.stores)
// iterating only through mongo stores
this.connections = _.mapValues(stores, (_store, storeName) => {
const store = _.merge({ }, _store)
if (!_.isString(store.uri))
throw new Error('Store have to contain "uri" option')
this.connections = new Map(Object.entries(stores).map(([ storeName, store ]) => {
store = Object.assign({ }, store)

if (typeof store.uri !== 'string')
throw new Error('Store must contain "uri" option')

if (!_.isObject(store.options))
store.options = {}
if (typeof store.options !== 'object')
store.options = { }

const connection = mongoose.createConnection(store.uri, store.options)
const models = _.pickBy(this.models, { connection: storeName })
const models = Object.values(this.models).filter(m => m.connection === storeName)

_.map(models, model => {
models.forEach(model => {
const schema = new mongoose.Schema(model.schema, model.schemaOptions)
// Bind statics & methods
schema.statics = model.statics
Expand All @@ -66,11 +61,11 @@ module.exports = class MongooseTrailpack extends DatastoreTrailpack {

//create model
this.orm[model.globalId] = connection.model(model.globalId, schema, model.tableName)
this.packs.mongoose.orm[model.identity] = this.orm[model.globalId]
this.orm[model.identity] = this.orm[model.globalId]
})

return connection
})
return [ storeName, connection ]
}))

this.app.orm = this.orm

Expand All @@ -81,18 +76,17 @@ module.exports = class MongooseTrailpack extends DatastoreTrailpack {
* Close all database connections
*/
unload () {
return Promise.all(
_.map(this.connections, connection => {
return new Promise((resolve, reject) => {
connection.close((err) => {
if (err)
return reject(err)

resolve()
})
const closeConnections = [ ]
this.connections.forEach(connection => {
closeConnections.push(new Promise((resolve, reject) => {
connection.close((err) => {
if (err) return reject(err)
resolve()
})
})
)
}))
})

return Promise.all(closeConnections)
}

constructor (app) {
Expand All @@ -108,15 +102,16 @@ module.exports = class MongooseTrailpack extends DatastoreTrailpack {
*/
migrate () {
const SchemaMigrationService = this.app.services.SchemaMigrationService
const database = this.app.config.database

if (database.models.migrate == 'none') return
if (this.app.config.get('stores.models.migrate') == 'none') return

return Promise.all(
_.map(this.connections, connection => {
if (database.models.migrate == 'drop') {
return SchemaMigrationService.drop(connection)
}
}))
const migrations = [ ]
this.connections.forEach((connection, storeName) => {
const migrateMethod = this.app.config.get(`stores.${storeName}.migrate`)
//console.log('migrating with migrate method', migrateMethod)
migrations.push(SchemaMigrationService[migrateMethod](connection))
})

return Promise.all(migrations)
}
}
50 changes: 23 additions & 27 deletions lib/transformer.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
'use strict'

const _ = require('lodash')

module.exports = {

/**
Expand All @@ -10,9 +6,9 @@ module.exports = {
* @return {Object}
*/
pickStores (stores) {
return _.pickBy(stores, (_store, name) => {
return (_.isString(_store.uri) && _.startsWith(_store.uri, 'mongodb://'))
})
return Object.entries(stores)
.filter(([ , store ]) => /^mongodb:\/\//.test(store.uri))
.reduce((stores, [ storeName, store ]) => Object.assign(stores, { [storeName]: store }), { })
},

/**
Expand All @@ -21,27 +17,27 @@ module.exports = {
* @return {Object}
*/
transformModels (app) {
const models = app.models
const dbConfig = app.config.database
return _.mapValues(models, (model, modelName) => {
const config = model.constructor.config(app, require('mongoose')) || { }
const schema = model.constructor.schema(app, require('mongoose')) || { }
const onSchema = config.onSchema || _.noop

return {
identity: modelName.toLowerCase(),
globalId: modelName,
tableName: config.tableName || modelName.toLowerCase(),
connection: config.store || dbConfig.models.defaultStore,
migrate: config.migrate || dbConfig.models.migrate,
schema: schema,
schemaOptions: config.schema,
statics: config.statics || {},
methods: config.methods || {},
onSchema: onSchema
}
return Object.entries(app.models)
.map(([ modelName, model ]) => {
const modelConfig = model.constructor.config(app, require('mongoose')) || { }
const storeConfig = app.config.get(`stores.${modelConfig.store}`)
const schema = model.constructor.schema(app, require('mongoose')) || { }
const onSchema = modelConfig.onSchema || function () { }

})
return {
identity: modelName.toLowerCase(),
globalId: modelName,
tableName: modelConfig.tableName || modelName.toLowerCase(),
connection: modelConfig.store,
migrate: modelConfig.migrate || storeConfig.migrate,
schema: schema,
schemaOptions: modelConfig.schema,
statics: modelConfig.statics || {},
methods: modelConfig.methods || {},
onSchema: onSchema
}
})
.reduce((models, model) => Object.assign(models, { [model.globalId]: model }), { })
}

}
6 changes: 2 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,13 @@
}
],
"dependencies": {
"lodash": "^4.0.0",
"mongoose": "^4.7.7",
"trailpack": "2.1.0",
"trailpack-datastore": "2.0.0"
"trailpack": "^3"
},
"devDependencies": {
"chai": "^3.5.0",
"eslint": "3.13.1",
"eslint-config-trails": "2.0.6",
"eslint-config-trails": "^3",
"mocha": "3.2.0",
"smokesignals": "2.1.0",
"trails": "2.0.0"
Expand Down
40 changes: 17 additions & 23 deletions test/app.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
'use strict'

const _ = require('lodash')
const smokesignals = require('smokesignals')
const User = require('./model/User')
const Role = require('./model/Role')

module.exports = _.defaultsDeep({
module.exports = Object.assign(smokesignals.FailsafeConfig, {
pkg: {
name: 'mongoose-trailpack-test'
},
Expand All @@ -24,29 +21,26 @@ module.exports = _.defaultsDeep({
require('../') // trailpack-mongoose
]
},
database: {
stores: {
teststore: {
uri: 'mongodb://localhost:27017/test',
options: {
stores: {
teststore: {
migrate: 'drop',
uri: 'mongodb://localhost:27017/test',
options: {

}
},
storeoverride: {
uri: 'mongodb://localhost:27017/test2',
options: {
}
},
storeoverride: {
migrate: 'drop',
uri: 'mongodb://localhost:27017/test2',
options: {

}
},
notMongoStore: {
uri: 'postgres://localhost:5432/tests',
options: {}
}
},
models: {
defaultStore: 'teststore',
migrate: 'drop'
notMongoStore: {
migrate: 'drop',
uri: 'postgres://localhost:5432/tests',
options: {}
}
}
}
}, smokesignals.FailsafeConfig)
})
2 changes: 1 addition & 1 deletion test/lib/transformer.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ describe('lib.Transformer', () => {
describe('#pickStores', () => {

it('should pick only stores for mongo', () => {
const stores = lib.Transformer.pickStores(global.app.config.database.stores)
const stores = lib.Transformer.pickStores(global.app.config.stores)
assert.equal(typeof stores, 'object')
assert.deepEqual(Object.keys(stores), [ 'teststore', 'storeoverride' ])
})
Expand Down
1 change: 0 additions & 1 deletion test/model/Role.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
'use strict'
const Model = require('trails/model')
const Schema = require('mongoose').Schema

Expand Down
2 changes: 1 addition & 1 deletion test/model/User.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
'use strict'
const Model = require('trails/model')
const Schema = require('mongoose').Schema

Expand Down Expand Up @@ -40,6 +39,7 @@ module.exports = class User extends Model {

static config(app, Mongoose) {
return {
store: 'teststore',
schema: {
timestamps: true,
versionKey: false
Expand Down
Loading