danecando / hapi-sequelize Goto Github PK
View Code? Open in Web Editor NEWHapi plugin for the Sequelize ORM
License: MIT License
Hapi plugin for the Sequelize ORM
License: MIT License
I can't find anything in the code that provides a callback once the db has authenticated. Is this planned?
What I'm looking for is something like this:
server.register([
{
register: require('hapi-sequelize'),
options: [
{
name: 'dbname', // identifier
models: ['./server/models/**/*.js'], // paths/globs to model files
sequelize: new Sequelize(config, opts), // sequelize instance
sync: true, // sync models - default false
forceSync: false, // force sync (drops tables) - default false
onConnect: function (database) {
const options = {
storage: 'sequelize',
storageOptions: {
sequelize: database,
},
migrations: {
params: [database.getQueryInterface(), database.constructor, function() {
throw new Error('Migration tried to use old style "done" callback. Please upgrade to "umzug" and return a promise instead.');
}],
path: __dirname + '/../migrations',
pattern: /\.js$/
}
};
const migrate = new Umzug(options);
migrate.up();
}
}
]
}
]);
If I need to access two databases in my application one could normally assign sequelize to two variables, assigning a database to each.
Since the hapi-sequelized plugin is accessed via request.server.plugins['hapi-sequelized']
is there a way to register this plugin twice and access it via different keys?
Hi Folks!
I created a fork of this project hapi-sequelizejs to maintain it and keep it up to date, since this one seems to be unsupported by it's author.
I will be looking into some of the issues that are open here. I'm already working on some improvements and tests. Next steps are update the documentation and update the plugin to support the latest Sequelize (4.x) and Hapi.js (15.x).
The fork (hapi-sequelizejs) is based on the pre-release v3.0.1 from this project (hapi-sequelize).
Versions before the original v3.0.1 are not supported by hapi-sequelizejs.
PR's are welcome. Thanks.
Hey, I couldn't find this package through npm. Are you planning on putting it up?
Hello,
I'm using this packages with given versions:
hapi: 13.4.1
hapi-sequelize: 3.0.1
sequelize: 3.23.3
npm: 3.8.9
node: 6.2.0
On server start, I get this error:
ValidationError: "value" at position 0 fails because [child "name" fails because ["name" is required]]. "value" must be an object at Object.exports.process (/home/kkochanski/Projects/default/social_media/node_modules/hapi-sequelize/node_modules/joi/lib/errors.js:152:19) at internals.Any._validateWithOptions (/home/kkochanski/Projects/default/social_media/node_modules/hapi-sequelize/node_modules/joi/lib/any.js:649:27) at root.validate (/home/kkochanski/Projects/default/social_media/node_modules/hapi-sequelize/node_modules/joi/lib/index.js:104:23) at Object.exports.register (/home/kkochanski/Projects/default/social_media/node_modules/hapi-sequelize/lib/index.js:49:26) at Object.target [as register] (/home/kkochanski/Projects/default/social_media/node_modules/hapi/node_modules/joi/lib/object.js:79:30) at each (/home/kkochanski/Projects/default/social_media/node_modules/hapi/lib/plugin.js:317:14) at iterate (/home/kkochanski/Projects/default/social_media/node_modules/hapi/node_modules/items/lib/index.js:36:13) at Object.exports.serial (/home/kkochanski/Projects/default/social_media/node_modules/hapi/node_modules/items/lib/index.js:39:9) at internals.Plugin.register (/home/kkochanski/Projects/default/social_media/node_modules/hapi/lib/plugin.js:320:11) at Object.<anonymous> (/home/kkochanski/Projects/default/social_media/server/server.js:41:8) at Module._compile (module.js:541:32) at Object.Module._extensions..js (module.js:550:10) at Module.load (module.js:458:32) at tryModuleLoad (module.js:417:12) at Function.Module._load (module.js:409:3) at Function.Module.runMain (module.js:575:10) at startup (node.js:160:18) at node.js:449:3
My options
which are validated by const validation = Joi.validate(options, Schema.options);
:
[ { database: 'social_media', user: 'kkochanski', pass: null, dialect: 'mysql', port: 3306, models: 'db/models/*.js', sequelize: { define: [Object] } } ]
Right now I don't have any idea what's going wrong. It was working few days ago. Can anyone help?
process.env.PWD would return undefined.... but process.cwd() works fine...
EDIT: Closed because I have a workaround which ignores this plugin.
Hi,
Attempting to implement via confidence in an app, and when I attempt to add the plugin I get:
RangeError: Maximum call stack size exceeded
Research suggests its something to with having the dialectOptions set (necessary to encrypt with Azure SQL)...
plugin: {
register: 'hapi-sequelize',
options: {
name: 'mydb',
models: './server/models/**/*.js',
sequelize: new Sequelize('DBNAME', 'username', 'password', {
host: 'xxx.database.windows.net', dialect: 'mssql', pool: {
max: 5,
min: 0,
idle: 10000
}, dialectOptions: {
encrypt: true
}
}), // sequelize instance
}
}
I have started digging through your code and may try a fix myself if needed.
Can you give a quick example of how I would run migrations generated by the CLI using this?
Hi,
How to add support for named instance on mssql?
Regards.
This issue would help #57 to be effective moving forward.
If this makes sense @danecando, I can take it.
node v0.12.0
hapijs v8.4.0
Im not sure if this is a issue with my setup or not. I have the same error while accessing db
via the server.plugins['hapi-sequelized']
too.
➜ test npm test
> [email protected] test /Users/sandeep/Downloads/hapi-sequelized-master
> lab
Unhandled rejection TypeError: Cannot read property 'db' of undefined
at /Users/sandeep/Downloads/hapi-sequelized-master/test/index.js:53:57
at done (/Users/sandeep/Downloads/hapi-sequelized-master/node_modules/hapi/node_modules/items/lib/index.js:22:21)
at /Users/sandeep/Downloads/hapi-sequelized-master/lib/index.js:49:20
at tryCatcher (/Users/sandeep/Downloads/hapi-sequelized-master/node_modules/sequelize/node_modules/bluebird/js/main/util.js:24:31)
at Promise._settlePromiseFromHandler (/Users/sandeep/Downloads/hapi-sequelized-master/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:454:31)
at Promise._settlePromiseAt (/Users/sandeep/Downloads/hapi-sequelized-master/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:530:18)
at Promise._settlePromises (/Users/sandeep/Downloads/hapi-sequelized-master/node_modules/sequelize/node_modules/bluebird/js/main/promise.js:646:14)
at bound (domain.js:254:14)
at Promise.runBound (domain.js:267:12)
at Async._drainQueue (/Users/sandeep/Downloads/hapi-sequelized-master/node_modules/sequelize/node_modules/bluebird/js/main/async.js:182:12)
at Async._drainQueues (/Users/sandeep/Downloads/hapi-sequelized-master/node_modules/sequelize/node_modules/bluebird/js/main/async.js:187:10)
at Immediate.Async.drainQueues [as _onImmediate] (/Users/sandeep/Downloads/hapi-sequelized-master/node_modules/sequelize/node_modules/bluebird/js/main/async.js:15:14)
at processImmediate [as _immediateCallback] (timers.js:358:17)
This option doesn't appear to be built into sequelize. I will test to see if this causes any conflicts with the library.
Anyone else want to see this added in the new version? (if possible)
Can the functionality of this plugin be extended to allow the additional documented options to be passed to the Sequelize constructor?
For example, it would be nice to set the timestamps
option globally, instead of for each model, like the Sequelize documentation allows:
http://sequelize.readthedocs.org/en/latest/docs/getting-started/#application-wide-model-options
In addition to model settings, it would also be convenient to be allowed to pass all the other Sequelize constructor options such options.logging
, options.replication
, etc
The version on npm is currently 3.0.1. I was getting errors and couldn't figure out why. Just checked and saw master is not updated with npm's current version.
At the moment the plugin calls Sequelize authenticate()
but does not handle the exception that might occur, resulting 404 route not found due to a silenced internal error.
I got a fix for it (still need to write some tests for it), what is the process on this repo to propose a change ? Simply create a fork then PR ?
Is it possible to use this module with a database connection string, rather than configuring each connection property individually?
When there is a runtime error like this:
ERROR: could not extend file "base/12407/1249": No space left on device
SUGERENCIA: Check free disk space.
Because of no left space and a config like this
options: {
...
sync: true,
app crashes with absolutely no useful info.
Should this be handled by hapi-sequelize? Not sure if it's already handled by sequelize itself.
When there is an issue with a model, such as a syntax error, there is only a light and undescriptive warning coming from sqlizr after it is loaded, due to this pull request:
My expectation is that I shouldn't be able to start the server if there is an error with one of the models, as that means the application behavior would almost definitely become unpredictable when certain models are available and others are not.
Maybe you have different reasoning, in which case perhaps some sort of promise on sqlizr and a config option on hapi-sequelize changing this behavior would be better.
Steps to reproduce: inside a handler, call request.getDb('i-am-a-invalid-name') and returns, in my case the last of 2 database connections.
Will be preferable throwing a KeyError exception or return a undefined value?
better doc$
Sequelize should be included as a peer dependency, rather than a normal dependency. That way it's guaranteed that the cli and the hapi plugin both use the exact same sequelize version.
at Promise$_settlePromiseFromHandler as _settlePromiseFromHandler
This is just a question.
I just wrote a unit test suite where I check the integrity of my models (password should not be < 8 etc.) but I have to perform a database connection on each test therefore my test are pretty slow (~350ms).
Here is an example of a basic test:
'use strict';
var assert = require('assert');
var config = require('../../config/config');
var Hapi = require('hapi');
describe('User module: [model]', function() {
var server = {};
beforeEach('Setting up the server', function() {
server = new Hapi.Server();
server.connection();
return server.register({
register: require('hapi-sequelize'),
options: {
database: config.get('/database/credentials').dbName,
user: config.get('/database/credentials').user,
pass: config.get('/database/credentials').pass,
dialect: config.get('/database/credentials').dialect,
port: config.get('/database/credentials').port,
models: 'app/modules/user/model.js',
logging: false
}
})
.then(function() {
var db = server.plugins['hapi-sequelize'].db;
return db.sequelize.sync({force: true})
.then(function() {
return server.initialize();
});
})
.catch(assert.ifError);
});
afterEach('Clear database/server connection', function() {
server.plugins['hapi-sequelize'].db.sequelize.close();
return server.stop();
});
describe('User model', function() {
it('should hash user\'s password', function() {
var User = server.plugins['hapi-sequelize'].db.sequelize.models.User;
return User.create({
email: '[email protected]',
password: 'iamapassword'
})
.then(function(user) {
assert.equal(user.password.length, 60);
})
.catch(assert.ifError);
});
});
});
Is it possible to test Model creation without actually using a database connection? Is it possible to mock it or something alike?
with hapi glue mainfest config:
{
plugin: 'hapi-sequelize',
options: {
name: 'create_trip',
models: [],
sequelize: new Sequelize(
'create_trip',
'root',
'root',
{
host: 'localhost'
}
),
}
}
throw error:
internals.Store.validate = function (node, path) {
^
RangeError: Maximum call stack size exceeded
I tried to use this plugin by installing it as npm module and then register as plugin to a Hapi server. It seems it's reading the files inside the hapi-sequelized folder under node_modules/ instead of reading the files in models/ folder.
Can the repository field be added to the package.json for this module so the below warning is not shown by npm?
npm WARN package.json [email protected] No repository field.
Any thoughts to exposing the models on the request object.. something like:
server.ext('onPreHandler', function(modelCollections) {
return function(request, reply) {
request.models = modelCollections;
reply.continue();
}
}(server.plugins['hapi-sequelized'].db.sequelize.models));
Then in routes you can get a model:
request.models.modelname ?
return (file.indexOf('.') !== 0) && (file !== 'index.js'));
should be
return (file.indexOf('.') !== 0) && (file !== 'index.js')
I wonder how to implement model association in this plugin as shown in sequelize site
var Player = this.sequelize.define('Player', {/* attributes */})
, Team = this.sequelize.define('Team', {/* attributes */});
Player.belongsTo(Team);
I have tried many ways to get this module to register properly with no success. It can be found under server.registrations, but does not appear in server.plugins.
My project uses glue/confidence with its composer. It started with frame (https://github.com/jedireza/frame) which uses mongodb and the goal was to port it to postgres using hapi-sequelize
I have used the previous version of hapi-sequelize in an older project successfully so am familiar with it. But in this new version having to instantiate the Sequelize object and pass it as an option is a challenge when using a manifest.
This project also uses pg and pg-pool so I know the connectivity to postgres works.
Tried the following:
I must be missing something, but I am the point where I can't afford to spend any more time on it and have to start coding this in sql using pg directly. Any hints or help is very much appreciated.
This is my latest attempt at implementing. When inspecting the server it shows under server.registrations and appears to be correct. It does not show up under plugins.
'use strict';
const Composer = require('./index');
var Config = require('./config');
Composer((err, server) => {
if (err) {
throw err;
}
//try registering hapi-sequelize here
var sq = require('sequelize');
var Seq = new sq(process.env.PGDATABASE, process.env.PGUSER, process.env.PGPASSWORD, {
host: process.env.PGHOST,
port: process.env.PGPORT,
dialect: 'postgres'});
server.register({
register: require('hapi-sequelize'),
options:
{
name: process.env.PGDATABASE,
models: Config.get('/hapiSequelize/models'),
sequelize: Seq,
sync: true,
debug: true
}
}
);
//check for hapi-sequelize
console.log(server.plugins)
//init any associations before starting server
var db = server.plugins['hapi-sequelize'].db;
var Models = db.sequelize.models;
var Account = Models.Account;
Account.associate(Models);
db.sequelize.sync().then(function () {
console.log("models synced. ignore 'not a valid model' warnings");
server.start(() => {
console.log('Started the app on port ' + server.info.port);
});
});
});
Is there some sort of conflict between modules? currently installed:
[email protected] C:\Data\Novo\gatewayserver
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected] extraneous
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]
If you generate a config and bootstrap file using sequelize-cli it generates a config file at config/config.json that looks like this:
{
"development": {
"username": null,
"password": null,
"database": "databse",
"host": "127.0.0.1",
"port": 5432,
"dialect": "postgres"
}
}
It would be nice if hapi-sequelized used the "username" and "password" keys that sequelize-cli generates instead of "user" and "pass" making it a bit more convenient to use the same config file:
var env = process.env.NODE_ENV || 'development';
var hapiSequelizeOptions = require('./config/database.json')[env];
var manifest = {
plugins: {
'hapi-sequelized': {
options: hapiSequelizeOptions
}
}
};
Instead of:
var manifest = {
plugins: {
'hapi-sequelized': {
options: {
database: hapiSequelizeOptions.database,
dialect: hapiSequelizeOptions.dialect,
host: hapiSequelizeOptions.host,
port: hapiSequelizeOptions.port,
user: hapiSequelizeOptions.username,
pass: hapiSequelizeOptions.password,
models: hapiSequelizeOptions.models
}
}
}
};
this allows saving date in DB at specified timezone
Is it possible to publish 2.2.0 to npm, I would like to switch to uri in my config
Thanks
It's like following when not using hapi-sequelized
(adapted from here)
// executed "after" `sequelize.sync(...)`
sequelize.addHook('afterBulkSync', function (options) {
// this = sequelize instance
// create stored procedures here ...
})
What's the best place to put above codes when using hapi-sequelized
? Is it possible to put this piece of codes in a model definition file? Thanks!
I am using hapi-sequelize in my project. working fine with mysql dialect in development and production mode, but sqlite dialect is not working properly. It does not create .sqlite file when specified in options.
server.register(
[
{
register: require('hapi-sequelized'),
options: {
dialect: 'sqlite',
storage: "test.sqlite",
models: 'models/**/*.js',
sequelize: {
define: {
underscoredAll: true
}
}
}
},
], function(err) {
if (err) {
console.error('failed to load plugin');
}
}
);
the above config options does not create sqlite file. can you help me where i am going wrong.
I am using postgres with sequelize. Here is what my code looks like:
server.register([
{
register: require('hapi-sequelizejs'), // eslint-disable-line global-require
options: {
name: Config.db.name,
models: ['./models/*.js'],
sequelize: new Sequelize(Config.db.name, Config.db.username, Config.db.password, {
host: Config.db.host,
dialect: 'postgres',
}),
sync: true,
},
},
])
When I log req.server.plugins['hapi-sequelizejs'][Config.db.name].getModels()
I get an empty object. Here is what my model definition looks like:
module.exports = (sequelize, DataTypes) => {
const schema = {
id: {
type: DataTypes.UUIDV4,
primaryKey: true,
},
name: DataTypes.STRING,
email: DataTypes.STRING,
gender: DataTypes.ENUM('male', 'female', 'other'),
};
return sequelize.define('User', schema);
};
Not sure what the problem is here.
P.S. I have confirmed that the location of the models glob is correct by manually using node-glob
.
update tests to cover new codes
I am currently trying to reduce our node_module folder with 53 MB hapi-sequelize
is our biggest dependency.
53M ./hapi-sequelize/node_modules
53M ./hapi-sequelize
I saw that the published packages include all devDependencies. I would think that this is not required and love to see future npm packages published without the devDependencies.
Installing the node_module manually without the devDependencies reduces the size to 3 MB :)
Did anyone manage to load fixtures using the sequelize-fixtures package alongside this plugin?
I tried to but I've been unsuccessful so far. I'm not sure whether it is possible as is or if I'm just not doing the right thing. If that's the former I'll try to make a PR.
I am trying to use hapi-sequelize for mysql connection. I did tried the workaround provided in the ticket 64 I am able to connect to mysql database. I am facing difficulty on how to use the models and other details to query the database. Please provide a sample example of using hapi-sequelize.
I am using hapi 15
server.register([
{
register: require('hapi-sequelize'),
options: [
{
name: 'create_trip', // identifier
models: ['./server/models/**/*.js'], // paths/globs to model files
sequelize: new Sequelize('create_trip', 'root', 'root', {
host: 'localhost'
}), // sequelize instance
sync: true, // sync models - default false
forceSync: false, // force sync (drops tables) - default false
onConnect: function (database) { // Optional
console.log('object');
}
}
]
}
]).then(() => {
server.start((error) => {
if (error) {
throw error;
}
console.log('Started the plot device on port ' + server.info.port);
});
}).catch((err) => {
console.log(err);
})
the error:
{ [ValidationError: "value" at position 0 fails because ["onConnect" is not allowed]. "value" must be an object]
isJoi: true,
name: 'ValidationError',
details:
[ { message: '"onConnect" is not allowed',
path: '0.onConnect',
type: 'object.allowUnknown',
context: [Object] },
{ message: '"value" must be an object',
path: 'value',
type: 'object.base',
context: [Object] } ],
_object:
[ { name: 'create_trip',
models: [Object],
sequelize: [Object],
sync: true,
forceSync: false,
onConnect: [Function: onConnect] } ],
annotate: [Function] }
would be nice:
modelsDir = options.modelsDir || '../../models';
or something...
It would be great to have a logging option to pass to the sync method. Might be easiest to pass the option directly so users could implement their own function, but could have examples showing how to use server.log
or similar.
Passing the sequelize instance in the options does not work with confidence and glue as the composer requires the manifest to be valid JSON.
When you search for "hapi sequelize" on npmjs.com, hapi-sequelized
comes up on page 4. Perhaps adding more keywords to the package.json
will help. Matching some of the ones used by Sequelize and others may help target the appropriate users:
[
"mysql",
"sqlite",
"postgresql",
"postgres",
"mssql",
"orm",
"plugin",
"database"
]
However, it doesn't make sense that some modules with nothing to do with sequelize are ranking higher than this one.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.