Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A little improvment for the Express middleware :) #92

Closed
wants to merge 1 commit into from
Closed
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
41 changes: 22 additions & 19 deletions lib/Express.js
Original file line number Diff line number Diff line change
@@ -1,40 +1,43 @@
var orm = require("./ORM");
var _models = {};
var _db = null;
var orm = require("./ORM");

var dbReady = null;

module.exports = function (uri, opts) {
var _db = null;
var _models = {};

opts = opts || {};

orm.connect(uri, function (err, db) {
if (err) {
if (typeof opts.error == "function") {
opts.error(err);
} else {
throw err;
}
return;
}

if (Array.isArray(_db)) {
_db.push(db);
} else if (_db !== null) {
_db = [ _db, db ];
} else {
_db = db;
}
_db = db;
if (typeof opts.define == "function") {
opts.define(db, _models);
opts.define(db, _models, function () {
if (Object.keys(_models).length > 0) {
_db = _models;
}
});
}
if(typeof(dbReady) == 'function') {
dbReady();
}
});

return function ORM(req, res, next) {
if (req.hasOwnProperty("models")) {
if(_db) {
req.db = _db;
return next();
} else {
dbReady = function dbReady () {
req.db = _db;
return next();
}
}

req.models = _models;
req.db = _db;

return next();
};
};