Skip to content

Commit

Permalink
Merge pull request #65 from actionhero/issue-63
Browse files Browse the repository at this point in the history
Resolves issue #63
  • Loading branch information
evantahler committed Dec 4, 2018
2 parents acb8e97 + 3eb6a4d commit ab506a6
Show file tree
Hide file tree
Showing 10 changed files with 3,342 additions and 3,239 deletions.
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto
26 changes: 24 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,36 @@ exports['default'] = {

For additional information on supported databases visit the [Sequelize Docs](http://docs.sequelizejs.com/manual/installation/getting-started).

### Add optional depenedencies
### Add optional dependencies
- For automatic fixures: `npm install sequelize-fixtures --save`
- For Sequelize CLI: `npm install --save-dev sequelize-cli`

### Configuration

A `./config/sequelize.js` file will be created which will store your database configuration. Read commented sections of configuration file for examples of multi-environment configurations.

To override the default location for models and/or migrations, use the `modelsDir` and `migrationsDir` configuration parameter with an array of paths relative to the project root.

```javascript
exports.default = {
sequelize: (api) => {
return {
'autoMigrate': true,
'loadFixtures': false,
'database': 'DEVELOPMENT_DB',
'dialect': 'mysql',
'port': 3306,
'host': '127.0.0.1',
'username': 'root',
'password': '',
'modelsDir': ['models', 'plugins/acl-plugin/models'], // Default: ['models']
'migrationsDir': ['migrations', 'plugins/acl-plugin/migrations'] // Default: ['migrations']
}
}
}

```

## [Models](http://docs.sequelizejs.com/en/latest/api/models)

Use the exports form of sequelize models in `./models` with the file name matching that of the model, IE:
Expand Down Expand Up @@ -180,4 +202,4 @@ module.exports = class AssociationsInitializer extends Initializer {

We use the `sequelize-fixtures` package to load in JSON-defined fixtures in the test NODE\_ENV. Store your fixtures in `./test/fixtures/*.json` or `./test/fixtures/*.yml`.

By default, `ah-sequelize-plugin` will **not** automatically load your fixtures when Actionhero starts up. You can enable this behaviour by adding `loadFixtures: true` to your sequelize config.
By default, `ah-sequelize-plugin` will **not** automatically load your fixtures when Actionhero starts up. You can enable this behavior by adding `loadFixtures: true` to your sequelize config.
98 changes: 59 additions & 39 deletions classes/sequelize.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,47 +18,61 @@ module.exports =
config
)

this.umzug = new Umzug({
storage: 'sequelize',
storageOptions: {
sequelize: this.sequelize
},
migrations: {
params: [
this.sequelize.getQueryInterface(),
this.sequelize.constructor,
() => {
throw new Error('Migration tried to use old style "done" callback. Please upgrade to "umzug" and return a promise instead.')
}],
path: path.join(api.projectRoot, 'migrations'),
pattern: /\.js$/
}
})
this.umzug = []
this.importMigrationsFromDirectory(config.migrationsDir || ['migrations'])
}

async connect () {
const importModelsFromDirectory = (dir) => {
fs.readdirSync(dir).forEach((file) => {
const filename = path.join(dir, file)
if (fs.statSync(filename).isDirectory()) {
return importModelsFromDirectory(filename)
}
if (path.extname(file) !== '.js') return
var nameParts = file.split('/')
var name = nameParts[(nameParts.length - 1)].split('.')[0]
var modelFunc = currySchemaFunc(require(filename))
this.sequelize.import(name, modelFunc)
api.watchFileAndAct(filename, async () => {
api.log(`*** Rebooting due to model change (${filename}) ***`, 'info')
delete require.cache[require.resolve(filename)]
delete this.sequelize.importCache[filename]
await api.commands.restart()
importMigrationsFromDirectory (dir) {
(Array.isArray(dir) ? dir : [dir])
.map(dir => path.normalize(path.join(api.projectRoot, dir)))
.forEach(dir => {
this.umzug.push(new Umzug({
storage: 'sequelize',
storageOptions: {
sequelize: this.sequelize
},
migrations: {
params: [
this.sequelize.getQueryInterface(),
this.sequelize.constructor,
() => {
throw new Error('Migration tried to use old style "done" callback. Please upgrade to "umzug" and return a promise instead.')
}],
path: dir,
pattern: /\.js$/
}
}))
})
}

importModelsFromDirectory (dir) {
(Array.isArray(dir) ? dir : [dir])
.map(dir => path.normalize(path.join(api.projectRoot, dir)))
.forEach(dir => {
fs.readdirSync(dir).forEach(file => {
const filename = path.join(dir, file)
if (fs.statSync(filename).isDirectory()) {
return this.importModelsFromDirectory(filename)
}
if (path.extname(file) !== '.js') return
let nameParts = file.split('/')
let name = nameParts[(nameParts.length - 1)].split('.')[0]
let modelFunc = currySchemaFunc(require(filename))
this.sequelize.import(name, modelFunc)

// watch model files for changes
api.watchFileAndAct(filename, async () => {
api.log(`*** Rebooting due to model change (${filename}) ***`, 'info')
delete require.cache[require.resolve(filename)]
delete this.sequelize.importCache[filename]
await api.commands.restart()
})
})
})
}
}

let dir = path.normalize(path.join(api.projectRoot, 'models'))
importModelsFromDirectory(dir)
async connect () {
this.importModelsFromDirectory(config.modelsDir || 'models')
api.models = this.sequelize.models
await this.test()
}
Expand All @@ -77,19 +91,25 @@ module.exports =
: options

await checkMetaOldSchema()
await this.umzug.execute(options)
for (const umzug of this.umzug) {
await umzug.execute(options)
}
}

async autoMigrate () {
if (config.autoMigrate === null || config.autoMigrate === undefined || config.autoMigrate) {
await checkMetaOldSchema()
await this.umzug.up()
for (const umzug of this.umzug) {
await umzug.up()
}
}
}

async migrateUndo () {
await checkMetaOldSchema()
await this.umzug.down()
for (const umzug of this.umzug) {
await umzug.down()
}
}

async test () {
Expand Down
Loading

0 comments on commit ab506a6

Please sign in to comment.