Skip to content

Commit

Permalink
Updates express middleware to support async definitions (#291)
Browse files Browse the repository at this point in the history
`next` argument is optional and if set it will block until it's called
  • Loading branch information
dresende committed Aug 20, 2013
1 parent d22d45b commit 2f85e30
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
4 changes: 3 additions & 1 deletion Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,10 @@ var orm = require('orm');
var app = express();

app.use(orm.express("mysql://username:password@host/database", {
define: function (db, models) {
define: function (db, models, next) {
models.person = db.define("person", { ... });

return next();
}
}));
app.listen(80);
Expand Down
13 changes: 10 additions & 3 deletions lib/Express.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ module.exports = function (uri, opts) {
_pending += 1;

orm.connect(uri, function (err, db) {
_pending -= 1;

if (err) {
if (typeof opts.error === "function") {
opts.error(err);
Expand All @@ -29,14 +27,21 @@ module.exports = function (uri, opts) {
} else {
_db = db;
}

if (typeof opts.define === "function") {
if (opts.define.length > 2) {
return opts.define(db, _models, function () {
return checkRequestQueue();
});
}

opts.define(db, _models);
}

return checkRequestQueue();
});

return function ORM(req, res, next) {
return function ORM_ExpressMiddleware(req, res, next) {
if (!req.hasOwnProperty("models")) {
req.models = _models;
req.db = _db;
Expand All @@ -52,6 +57,8 @@ module.exports = function (uri, opts) {
};

function checkRequestQueue() {
_pending -= 1;

if (_pending > 0) return;
if (_queue.length === 0) return;

Expand Down

0 comments on commit 2f85e30

Please sign in to comment.