Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

ah-sequelize-plugin

Package Overview
Dependencies
Maintainers
6
Versions
69
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ah-sequelize-plugin - npm Package Compare versions

Comparing version 0.9.0 to 1.0.0

classes/sequelize.js

64

config/sequelize.js
exports.default = {
sequelize: function(api){
return {
"autoMigrate" : true,
"loadFixtures": false,
"database" : "DEVELOPMENT_DB",
"dialect" : "mysql",
"port" : 3306,
"host" : "127.0.0.1",
"username" : "root",
"password" : ""
};
sequelize: (api) => {
return {
'autoMigrate': true,
'loadFixtures': false,
'database': 'DEVELOPMENT_DB',
'dialect': 'mysql',
'port': 3306,
'host': '127.0.0.1',
'username': 'root',
'password': ''
}
};
}
}

@@ -19,16 +19,34 @@ // For sequelize-cli

exports.development = exports.default.sequelize();
//exports.test = merge(exports.test);
//exports.production = merge(exports.production);
exports.development = exports.default.sequelize()
// exports.test = merge(exports.test);
// exports.production = merge(exports.production);
var merge = function(overlayFn) {
var mergeObj = {};
for (var attrname in exports.default.sequelize()) { mergeObj[attrname] = exports.default.sequelize()[attrname]; }
if (typeof(overlayFn) !== 'undefined') for (var attrname in overlayFn.sequelize()) { mergeObj[attrname] = overlayFn.sequelize()[attrname]; }
// Uncomment merge function when adding exports
// Map over AH's sequelize fn
mergeObj.sequelize = overlayFn.sequelize;
return mergeObj;
};
// const merge = (overlayFn) => {
// let mergeObj = {}
// for (let attrname in exports.default.sequelize()) {
// mergeObj[attrname] = exports.default.sequelize()[attrname]
// }
// if (typeof (overlayFn) !== 'undefined') {
// for (var attrname in overlayFn.sequelize()) {
// mergeObj[attrname] = overlayFn.sequelize()[attrname]
// }
// }
// Example test configuration (using sqlite in-memory)
// exports.test = {
// sequelize: (api) => {
// return {
// 'autoMigrate': true,
// 'loadFixtures': false,
// 'logging': false,
// 'dialect': 'sqlite',
// 'storage': ':memory:',
// 'host': 'localhost'
// }
// }
// }
// You can define even more elaborate configurations (including replication).

@@ -35,0 +53,0 @@ // See http://sequelize.readthedocs.org/en/latest/api/sequelize/index.html for more information

@@ -1,167 +0,24 @@

var path = require('path');
var fs = require('fs');
var Sequelize = require('sequelize');
var Umzug = require('umzug');
const { Initializer, api } = require('actionhero')
const SequelizePlugin = require('../classes/sequelize.js')
module.exports = {
loadPriority: 121, // aligned with actionhero's redis and logger initializer
startPriority: 121, // aligned with actionhero's redis and logger initializer
stopPriority: 121, // aligned with actionhero's redis and logger initializer
module.exports =
class SequelizeInitializer extends Initializer {
constructor () {
super()
this.name = 'sequelize'
this.loadPriority = 101
this.startPriority = 101
this.stopPriority = 300
}
initialize: function(api, next) {
api.models = {};
api.config.sequelize.logging = api.log;
var sequelizeInstance = new Sequelize(
api.config.sequelize.database,
api.config.sequelize.username,
api.config.sequelize.password,
api.config.sequelize
);
async initialize () {
api.models = {}
api.sequelize = new SequelizePlugin()
}
var umzug = new Umzug({
storage: 'sequelize',
storageOptions: {
sequelize: sequelizeInstance
},
migrations: {
params: [sequelizeInstance.getQueryInterface(), sequelizeInstance.constructor, function() {
throw new Error('Migration tried to use old style "done" callback. Please upgrade to "umzug" and return a promise instead.');
}],
path: api.projectRoot + '/migrations',
pattern: /\.js$/
}
});
var currySchemaFunc = function(SchemaExportFunc) {
return function(a, b) {
return SchemaExportFunc(a, b, api);
};
};
api.sequelize = {
sequelize: sequelizeInstance,
umzug: umzug,
migrate: function(opts, next) {
if (typeof opts === "function") {
next = opts;
opts = null;
}
opts = opts === null ? {
method: 'up'
} : opts;
checkMetaOldSchema(api, umzug).then(function() {
return umzug.execute(opts);
}).then(function() {
next();
});
},
migrateUndo: function(next) {
checkMetaOldSchema(api, umzug).then(function() {
return umzug.down();
}).then(function() {
next();
});
},
connect: function(next) {
function importModelsFromDirectory(dir) {
fs.readdirSync(dir).forEach(function(file) {
if (fs.statSync(path.join(dir, file)).isDirectory())
return importModelsFromDirectory(path.join(dir, file))
if (path.extname(file) !== '.js') return;
var nameParts = file.split("/");
var name = nameParts[(nameParts.length - 1)].split(".")[0];
var modelFunc = currySchemaFunc(require(dir + '/' + file));
api.sequelize.sequelize.import(name, modelFunc);
});
}
var dir = path.normalize(api.projectRoot + '/models');
importModelsFromDirectory(dir);
api.models = api.sequelize.sequelize.models;
api.sequelize.test(next);
},
loadFixtures: function(next) {
if (api.config.sequelize.loadFixtures) {
var SequelizeFixtures = require('sequelize-fixtures');
var options = { log: (api.config.logging)? console.log : function(){}};
SequelizeFixtures.loadFile(api.projectRoot + '/test/fixtures/*.{json,yml,js}', api.models, options).then(function() {
next();
});
} else {
next();
}
},
autoMigrate: function(next) {
if (api.config.sequelize.autoMigrate === null ||
api.config.sequelize.autoMigrate === undefined ||
api.config.sequelize.autoMigrate) {
checkMetaOldSchema(api, umzug).then(function() {
return umzug.up();
}).then(function() {
next();
});
} else {
next();
}
},
// api.sequelize.test([exitOnError=true], next);
// Checks to see if mysql can be reached by selecting the current time
// Arguments:
// - next (callback function(err)): Will be called after the test is complete
// If the test fails, the `err` argument will contain the error
test: function(next) {
var query = "SELECT NOW()";
if (api.config.sequelize.dialect == 'mssql') query = "SELECT GETDATE();";
if (api.config.sequelize.dialect == 'sqlite') query = "SELECT strftime('%s', 'now');";
api.sequelize.sequelize.query(query).then(function() {
next();
}).catch(function(err) {
api.log(err, 'warning');
console.log(err);
next(err);
});
}
};
next();
},
start: function(api, next) {
api.sequelize.connect(function(err) {
if (err) {
return next(err);
}
api.sequelize.autoMigrate(function() {
api.sequelize.loadFixtures(next);
});
});
async start () {
await api.sequelize.connect()
await api.sequelize.autoMigrate()
await api.sequelize.loadFixtures()
}
}
};
var checkMetaOldSchema = function(api, umzug) {
// Check if we need to upgrade from the old sequelize migration format
return api.sequelize.sequelize.query('SELECT * FROM SequelizeMeta', {
raw: true
}).then(function(raw) {
var rows = raw[0];
if (rows.length && rows[0].hasOwnProperty('id')) {
throw new Error('Old-style meta-migration table detected - please use `sequelize-cli`\'s `db:migrate:old_schema` to migrate.');
}
}).catch(Sequelize.DatabaseError, function(err) {
var noTableMsg = 'No SequelizeMeta table found - creating new table. (Make sure you have \'migrations\' folder in your projectRoot!)';
if (process.env.NODE_ENV != "test") {
api.log(noTableMsg);
console.log(noTableMsg);
}
});
};
{
"author": "Evan Tahler <evantahler@gmail.com>",
"name": "ah-sequelize-plugin",
"description": "I use sequelize in actionhero as an ORM",
"version": "0.9.0",
"description": "Use Sequelize in ActionHero",
"version": "1.0.0",
"homepage": "http://actionherojs.com",

@@ -22,10 +22,16 @@ "repository": {

"engines": {
"node": ">=0.8.0"
"node": ">=8.0.0",
"npm": "5.3.x"
},
"dependencies": {
"mkdirp": "^0.3.5",
"umzug": "^1.6.0"
"mkdirp": "^0.5.1",
"umzug": "^2.0.1"
},
"devDependencies": {},
"optionalDependencies": {},
"devDependencies": {
"standard": "^10.0.3"
},
"peerDependencies": {
"sequelize": ">=3.0.0",
"actionhero": ">=18.0.0"
},
"scripts": {

@@ -32,0 +38,0 @@ "postinstall": "node scripts/postinstall.js"

@@ -7,17 +7,28 @@ ![plugin](https://i.imgur.com/nd1btLt.png)

## Notes
Version 0.9.0 has a [breaking change](https://github.com/evantahler/ah-sequelize-plugin/pull/30) regarding model names.
Versions `>=1.0.0` are only compatible with ActionHero versions `>=18.0.0`.
For versions compatible with ActionHero versions prior to `18.0.0`, use version [`0.9.0`](https://github.com/actionhero/ah-sequelize-plugin/releases/tag/v0.9.0).
## Setup
- install this plugin: `npm install ah-sequelize-plugin --save`
- be sure to enable the plugin within actionhero (`config/plugins.js`) or If you're using actionhero 13 or higher make sure you linked/included the plugin using `npm run actionhero link -- --name ah-sequelize-plugin`
- you will need to add the sequelize package (`npm install sequelize --save`) to your package.json
- you will need to add the sequelize-fixtures package (`npm install sequelize-fixtures --save`) to your package.json
- you will need to add the mysql (or other supported database) package (`npm install mysql --save`) to your package.json
- there are many options you can pass to sequelize. You can learn more here: http://sequelize.readthedocs.org/en/latest/api/sequelize/index.html
- you will need to add the sequelize-cli package (`npm install sequelize-cli`) to your package.json
- you could install it globally instead (`npm install -g sequelize-cli`)
- Install this plugin: `npm install ah-sequelize-plugin --save`
- Link the plugin: `npm run actionhero link -- --name ah-sequelize-plugin`
- Add sequelize package: `npm install sequelize --save`
A `./config/sequelize.js` file will be created which will store your database configuration
### Add supported database packages
- MySQL: `npm install mysql2 --save`
- SQLite: `npm install sqlite3 --save`
- Postgress: `npm install --save pg pg-hstore`
- MSSQL: `npm install --save tedious`
For additional information on supported databases visit the [Sequelize Docs](http://docs.sequelizejs.com/manual/installation/getting-started).
### Add optional depenedencies
- 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.
## [Models](http://docs.sequelizejs.com/en/latest/api/models)

@@ -28,11 +39,34 @@

```javascript
module.exports = function(sequelize, DataTypes, api) {
return sequelize.define("Project", {
name: DataTypes.STRING,
description: DataTypes.TEXT
// from ./models/user.js
module.exports = function (sequelize, DataTypes, api) {
// Define model structure and options
const model = sequelize.define('user', {
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true
}
}, {
paranoid: true
})
// Attach Class methods
model.rehydrate = function (user) {
return this.build(user)
}
// Attach Instance methods
model.prototype.apiData = function () {
return {
id: this.id
}
}
return model
}
```
Models are loaded into `api.models`, so the example above would be `api.models.Project`. These module.exports allow for a third optional parameter "api" which is the ActionHero API object. This can be used to access configs and initializer functions, among other things.
Models are loaded into `api.models`, so the example above would be `api.models.user`. These module.exports allow for a third optional parameter "api" which is the ActionHero API object. This can be used to access configs and initializer functions, among other things.

@@ -47,43 +81,37 @@ ## [Migrations](http://docs.sequelizejs.com/en/latest/api/migrations)

var Promise = require('bluebird');
module.exports = {
up: async function (migration, DataTypes) {
await migration.createTable('users', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: DataTypes.STRING,
email: DataTypes.STRING,
phone: DataTypes.STRING,
passwordHash: DataTypes.TEXT,
passwordSalt: DataTypes.TEXT,
createdAt: DataTypes.DATE,
updatedAt: DataTypes.DATE
})
module.exports = {
up: function(migration, DataTypes) {
return Promise.all([
migration.createTable('users', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: DataTypes.STRING,
email: DataTypes.STRING,
phone: DataTypes.STRING,
passwordHash: DataTypes.TEXT,
passwordSalt: DataTypes.TEXT,
createdAt: DataTypes.DATE,
updatedAt: DataTypes.DATE
})
]).then(function(){
return Promise.all([
migration.addIndex('users', ['email'], {
indexName: 'email_index',
indicesType: 'UNIQUE'
}),
migration.addIndex('users', ['name'], {
indexName: 'name_index',
indicesType: 'UNIQUE'
}),
migration.addIndex('users', ['phone'], {
indexName: 'phone_index',
indicesType: 'UNIQUE'
})
]);
});
await migration.addIndex('users', ['email'], {
indexName: 'email_index',
indicesType: 'UNIQUE'
})
await migration.addIndex('users', ['name'], {
indexName: 'name_index',
indicesType: 'UNIQUE'
})
await migration.addIndex('users', ['phone'], {
indexName: 'phone_index',
indicesType: 'UNIQUE'
})
},
down: function(migration, DataTypes) {
return Promise.all([
migration.dropTable('users')
]);
down: async function (migration, DataTypes) {
await migration.dropTable('users')
}

@@ -107,14 +135,17 @@ }

```javascript
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define("User", {
username: DataTypes.STRING
}, {
classMethods: {
associate: function(models) {
User.hasMany(models.Task)
}
}
});
return User;
};
module.exports = function (sequelize, DataTypes, api) {
const model = sequelize.define('user', {
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true
}
})
model.associate = function (models) {
this.hasMany(models.email)
}
return model
}
```

@@ -125,24 +156,25 @@

```javascript
module.exports = {
loadPriority: 1000,
startPriority: 1002, // priority has to be after models have been loaded
stopPriority: 1000,
const ActionHero = require('actionhero')
const api = ActionHero.api
associations: {},
module.exports =
class AssociationsInitializer extends ActionHero.Initializer {
constructor () {
super()
this.name = 'associations'
this.loadPriority = 1000
this.startPriority = 1002
this.stopPriority = 1000
}
initialize: function (api, next) {
next();
},
start: function (api, next) {
for (var model in api.models) {
if (api.models[model].associate) {
api.models[model].associate(api.models)
}
}
next();
},
stop: function (api, next) {
next();
initialize () { }
start () {
api.models.filter(m => typeof m.associate === 'function')
.forEach(m => m.associate(api.models))
}
};
stop () { }
}
```

@@ -149,0 +181,0 @@

#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
const fs = require('fs')
const path = require('path')
const mkdirp = require('mkdirp')
var projectConfigDir = path.normalize(process.cwd() + '/../../config/');
var localConfigFile = path.normalize(__dirname + '/../config/sequelize.js');
var projectConfigFile = path.normalize(process.cwd() + '/../../config/sequelize.js');
const projectConfigFile = path.normalize(process.cwd() + '/../../config/sequelize.js')
var localRcFile = path.normalize(__dirname + '/../config/.sequelizerc');
var projectRcFile = path.normalize(process.cwd() + '/../../.sequelizerc');
const localRcFile = path.normalize(path.join(__dirname, '/../config/.sequelizerc'))
const projectRcFile = path.normalize(process.cwd() + '/../../.sequelizerc')
try {
fs.lstatSync(projectConfigFile);
fs.lstatSync(projectConfigFile)
} catch (ex) {
//unable to stat file because it doesn't exist
console.log("copying " + localConfigFile + " to " + projectConfigFile);
mkdirp.sync(path.normalize(projectConfigDir));
fs.createReadStream(localConfigFile).pipe(fs.createWriteStream(projectConfigFile));
// Only try to copy the files required for cli operations if sequelize.js is being newly created.
try {
fs.lstatSync(projectRcFile);
fs.lstatSync(projectRcFile)
} catch (ex) {
console.log("copying " + localRcFile + " to " + projectRcFile);
fs.createReadStream(localRcFile).pipe(fs.createWriteStream(projectRcFile));
console.log('copying ' + localRcFile + ' to ' + projectRcFile)
fs.createReadStream(localRcFile).pipe(fs.createWriteStream(projectRcFile))
}
}
['models', 'test/fixtures'].forEach(function(f){
mkdirp.sync(path.normalize(process.cwd() + '/../../' + f));
});
['models', 'test/fixtures'].forEach(function (f) {
mkdirp.sync(path.normalize(process.cwd() + '/../../' + f))
})
console.warn('Warning:');
console.warn('For actionhero 13 or higher please make sure you link this plugin.');
console.warn('npm run actionhero link -- --name ah-sequelize-plugin');
console.warn('To read more about this, http://www.actionherojs.com/docs/#plugins');
console.warn('Notice:')
console.warn('npm run actionhero link -- --name ah-sequelize-plugin')
console.warn('To read more about this, https://docs.actionherojs.com/tutorial-plugins.html')
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc