Skip to content

Commit

Permalink
Merge pull request #11 from sequelize/feature/models
Browse files Browse the repository at this point in the history
Model loader
  • Loading branch information
janmeier committed Jun 15, 2014
2 parents e5bc3ad + b6b6744 commit 4a04a6f
Show file tree
Hide file tree
Showing 13 changed files with 304 additions and 77 deletions.
17 changes: 10 additions & 7 deletions bin/sequelize
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@

'use strict';

var spawn = require('child_process').spawn
, fs = require('fs')
, path = require('path')
, gulp = path.resolve(__dirname, '..', 'node_modules', '.bin', 'gulp')
, args = process.argv.slice(2)
, yargs = require('yargs')
, _ = require('lodash')
var spawn = require('child_process').spawn
, fs = require('fs')
, path = require('path')
, gulp = path.resolve(__dirname, '..', 'node_modules', '.bin', 'gulp')
, args = process.argv.slice(2)
, yargs = require('yargs')
, _ = require('lodash')
, helpers = require(path.resolve(__dirname, '..', 'lib', 'helpers'))

if (!fs.existsSync(gulp)) {
gulp = path.resolve(process.cwd(), 'node_modules', '.bin', 'gulp')
Expand Down Expand Up @@ -54,6 +55,8 @@ if (_.contains(args, '--harmony')) {

var call = spawn(process.argv[0], args)

helpers.view.teaser()

call.stdout.on('data', function(data) {
var lines = data.toString().split("\n")
, output = ""
Expand Down
29 changes: 29 additions & 0 deletions lib/assets/models/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
var fs = require('fs')
, path = require('path')
, Sequelize = require('sequelize')
, lodash = require('lodash')
, env = process.env.NODE_ENV || 'development'
, config = require(__CONFIG_FILE__)[env]
, sequelize = new Sequelize(config.database, config.username, config.password, config)
, db = {}

fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== 'index.js')
})
.forEach(function(file) {
var model = sequelize.import(path.join(__dirname, file))
db[model.name] = model
})

Object.keys(db).forEach(function(modelName) {
if ('associate' in db[modelName]) {
db[modelName].associate(db)
}
})

module.exports = lodash.extend({
sequelize: sequelize,
Sequelize: Sequelize
}, db)
14 changes: 14 additions & 0 deletions lib/helpers/asset-helper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
var fs = require('fs-extra')
, path = require('path')

module.exports = {
copy: function (from, to) {
fs.copySync(path.resolve(__dirname, '..', 'assets', from), to)
},

injectConfigFilePath: function(filePath, configPath) {
var fileContent = fs.readFileSync(filePath).toString()
fs.writeFileSync(filePath, fileContent.replace('__CONFIG_FILE__', configPath)
)
}
}
8 changes: 4 additions & 4 deletions lib/helpers/gulp-helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ module.exports = {
task.descriptions.short,
task.dependencies || [],
function() {
helpers.view.teaser()
task.task()
}, {
aliases: task.aliases || []
Expand All @@ -24,7 +23,6 @@ module.exports = {
"help:" + taskName,
false,
function() {
helpers.view.teaser()
helpers.view.log(clc.bold("COMMANDS"))

var commands = [ taskName ].concat(task.aliases || [])
Expand Down Expand Up @@ -69,9 +67,11 @@ module.exports = {
getGlobalOptions: function() {
return {
"--env": "The environment to run the command in. " + clc.blueBright("Default: development"),
"--options-path": "The path to a JSON file with additional options. " + clc.blueBright("Default: none"),
"--coffee": "Enables coffee script support. " + clc.blueBright("Default: false"),
"--config": "The path to the config file. " + clc.blueBright("Default: config/config.json")
"--config": "The path to the config file. " + clc.blueBright("Default: config/config.json"),
"--options-path": "The path to a JSON file with additional options. " + clc.blueBright("Default: none"),
"--migrations-path": "The path to the migrations folder. " + clc.blueBright("Default: migrations"),
"--models-path": "The path to the models folder." + clc.blueBright("Default: models")
}
},

Expand Down
66 changes: 66 additions & 0 deletions lib/helpers/init-helper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
var helpers = require(__dirname)
, args = require('yargs').argv
, path = require('path')
, fs = require('fs')
, clc = require('cli-color')

module.exports = {
notifyAboutExistingFile: function(file) {
helpers.view.log('The file ' + clc.blueBright(file) + ' already exists. Run "sequelize init --force" to overwrite it.')
},

createFolder: function(folderName, folder, force) {
if (force) {
console.log('Deleting the ' + folderName + 'folder. (--force)')

try {
fs.readdirSync(folder).forEach(function(filename) {
fs.unlinkSync(folder + '/' + filename)
})
} catch(e) {
console.log(e)
}

try {
fs.rmdirSync(folder)
console.log('Successfully deleted the ' + folderName + ' folder.')
} catch(e) {
console.log(e)
}
}

try {
helpers.generic.mkdirp(folder)
console.log('Successfully created ' + folderName + ' folder at "' + folder + '".')
} catch(e) {
console.log(e)
}
},

createMigrationsFolder: function(force) {
this.createFolder('migrations', helpers.path.getMigrationsPath(), force)
},

createModelsFolder: function(force) {
this.createFolder('models', helpers.path.getModelsPath(), force)
},

createModelsIndexFile: function(force) {
var modelsPath = helpers.path.getModelsPath()
, indexPath = path.resolve(modelsPath, 'index.js')

if (!fs.existsSync(modelsPath)) {
helpers.view.log('Models folder not available.')
} else if (fs.existsSync(indexPath) && !force) {
this.notifyAboutExistingFile(indexPath)
} else {
var relativeConfigPath = path.relative(
helpers.path.getModelsPath(),
helpers.config.getConfigFile()
)

helpers.asset.copy('models/index.js', indexPath)
helpers.asset.injectConfigFilePath(indexPath, "__dirname + '/" + relativeConfigPath + "'")
}
}
}
39 changes: 0 additions & 39 deletions lib/helpers/migration-helper.js

This file was deleted.

14 changes: 14 additions & 0 deletions lib/helpers/path-helper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
var helpers = require(__dirname)
, args = require('yargs').argv
, path = require('path')
, fs = require('fs')

module.exports = {
getMigrationsPath: function() {
return args.migrationsPath || path.resolve(process.cwd(), 'migrations')
},

getModelsPath: function() {
return args.modelsPath || path.resolve(process.cwd(), 'models')
}
}
17 changes: 16 additions & 1 deletion lib/helpers/view-helper.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
var helpers = require(__dirname)
, clc = require('cli-color')
, _ = require('lodash')

module.exports = {
teaser: function() {
Expand All @@ -18,5 +19,19 @@ module.exports = {
this.log()
},

log: console.log
log: console.log,

pad: function(s, smth) {
var margin = smth

if (_.isObject(margin)) {
margin = Object.keys(margin)
}

if (Array.isArray(margin)) {
margin = Math.max.apply(null, margin.map(function(o) { return o.length }))
}

return s + new Array(margin - s.length + 1).join(" ")
}
}
2 changes: 1 addition & 1 deletion lib/tasks/db.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ var getMigrator = function(callback) {
if (helpers.config.configFileExists() || args.url) {

var sequelize = getSequelizeInstance()
, migratorOptions = { path: helpers.migration.getMigrationsPath() }
, migratorOptions = { path: helpers.path.getMigrationsPath() }

if (helpers.config.supportsCoffee()) {
migratorOptions = _.merge(migratorOptions, { filesFilter: /\.js$|\.coffee$/ })
Expand Down
77 changes: 68 additions & 9 deletions lib/tasks/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,92 @@ var path = require('path')
, helpers = require(path.resolve(__dirname, '..', 'helpers'))
, args = require('yargs').argv
, clc = require('cli-color')
, _ = require('lodash')

module.exports = {
"init": {
descriptions: {
short: "Initializes the project.",
long: [
"The command will initialize the current directory. The result",
"will be a 'config' as well as a 'migration' folder. Furthermore",
"'config/config.json' will be generated.",
],
long: (function() {
var result = [
"The command will initialize the current directory.",
"In detail this means, that you will find the following items afterwards:",
"",
]

var items = {
"config": "A folder that contains the config files.",
"config/config.json": "A file that contains the configuration for the ORM.",
"migrations": "A folder that containts the migration files.",
"models": "A folder that contains the model files.",
"models/index.js": "A file that can be required to load all the models."
}

_.each(items, function(value, key) {
result.push([
clc.blueBright(helpers.view.pad(key, items)),
value
].join(" "))
})

result = result.concat([
"",
"Most of the files and folders can be changed to fit custom folder structures.",
"Check the options for further information."
])

return result
})(),

options: {
"--force": "Will drop the existing config folder and re-create it. " + clc.blueBright("Default: false"),
"--migrations-path": "The path to the migrations folder. " + clc.blueBright("Default: migrations/")
"--force": "Will drop the existing config folder and re-create it. " + clc.blueBright("Default: false")
}
},

dependencies: [
'init:config',
'init:migrations',
'init:models'
],

task: function() {}
},

"init:config": {
descriptions: {
short: "Initializes the configuration."
},

task: function() {
if (!helpers.config.configFileExists() || !!args.force) {
helpers.config.writeDefaultConfig()

console.log('Created "' + helpers.config.relativeConfigFile() + '"')
} else {
console.log('The file "' + helpers.config.relativeConfigFile() + '" already exists. Run "sequelize init --force" to overwrite it.')
helpers.init.notifyAboutExistingFile(helpers.config.relativeConfigFile())
process.exit(1)
}
}
},

helpers.migration.createMigrationsFolder(!!args.force)
"init:models": {
descriptions: {
short: "Initializes the models."
},

task: function() {
helpers.init.createModelsFolder(!!args.force)
helpers.init.createModelsIndexFile(!!args.force)
}
},

"init:migrations": {
descriptions: {
short: "Initializes the migrations."
},

task: function() {
helpers.init.createMigrationsFolder(!!args.force)
}
}
}
6 changes: 3 additions & 3 deletions lib/tasks/migration.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ module.exports = {
task: function() {
var config = null

helpers.migration.createMigrationsFolder()
helpers.init.createMigrationsFolder()

try {
config = helpers.config.readConfig()
Expand All @@ -70,11 +70,11 @@ module.exports = {
!!args.name ? args.name : 'unnamed-migration'
].join('-') + migrationExtension

fs.writeFileSync(helpers.migration.getMigrationsPath() + '/' + migrationName, getSkeleton())
fs.writeFileSync(helpers.path.getMigrationsPath() + '/' + migrationName, getSkeleton())

console.log(
'New migration "' + migrationName + '" was added to "' +
path.relative(process.cwd(), helpers.migration.getMigrationsPath()) + '/".'
path.relative(process.cwd(), helpers.path.getMigrationsPath()) + '/".'
)
}
}
Expand Down
Loading

0 comments on commit 4a04a6f

Please sign in to comment.