Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Node.js Async Returns with "require" (Node ORM)

I'm using the Node.js ORM module : https://github.com/dresende/node-orm

I'm able to create a model by doing this:

    var orm = require("orm");
    var db = orm.connect("creds", function (success, db) {
        if (!success) {
            console.log("Could not connect to database!");
            return;
        }

      var Person = db.define("person", {
        "name"   : { "type": "string" },
        "surname": { "type": "string", "default": "" },
        "age"    : { "type": "int" }
      });
    });

The problem is that I want to put Person (and all other models for that matter) in external includes.

If I do something like this:

   require("./models/person.js");

I can't use the db variable inside of that, because it only exists in the context of the callback function for orm.connect(). I can't move orm.connect to the require (person.js) and do a module.export for the model info, because in the parent script, the require will happen and then the model won't be ready by the next line, since it's not waiting on the callback. IE

//person.js
// db and orm get defined up here as before
Person = {}; // code from above, with the define and etc. 
Module.exports = Person;
//app.js 
person = require("./models/person.js");
console.log(person); // returns undefined, connect callback isn't done yet 

I feel like there's an obvious way to do this.

like image 276
NateDSaint Avatar asked Jan 17 '23 15:01

NateDSaint


1 Answers

Perhaps could make the person.js's export into a function, and pass in db? Like this:

//app.js
var orm = require("orm");
var db = orm.connect("creds", function (success, db) {
    if (!success) {
        console.log("Could not connect to database!");
        return;
    }

  var Person = require("./models/person.js")(db);
});

//person.js
module.exports = function(db){
    return db.define("person", {
        "name"   : { "type": "string" },
        "surname": { "type": "string", "default": "" },
        "age"    : { "type": "int" }
    });
}
like image 119
iContaminate Avatar answered Jan 30 '23 00:01

iContaminate