Reputation: 528
I'm new to node.js (and javascript), and I'm following a tutorial on how to get a good structure for an application.
First, I wanted to have my routes in a separate folder.
Let's say this is my main.js :
var express = require('express');
const PORT = 3000;
const app = express();
app.set("json spaces", 2);
require('./routes')(app);
app.listen(PORT, function() {
console.log(`users-jwt-api - Port ${PORT}`)
});
In my "routes" folder, I have two files : index.js, used to load others files, and user.js
index.js :
var fs = require('fs');
module.exports = function(app){
fs.readdirSync(__dirname).forEach(function(file) {
if (file == "index.js") return;
var name = file.substr(0, file.indexOf('.'));
require('./' + name)(app);
});
}
user.js :
module.exports = function(app) {
app.get('/users', function(req, res) {
//no bd yet, returning static data, and dont want it here, but in a model
res.json({users:[{username: "titi", password:"toto"},{username: "tata", password:"tutu"}]});
});
};
This works like a charm ! Fine.
But, to be clear, I don't want any database code in my routes files, so I try to add a "models" folder. I put inside an index.js, just as for the routes, and a users.js like this :
module.exports = function(app) {
return {
findAll: function(params, callback) {
//no db yet
return callback([{username: "titi", password:"toto"},{username: "tata", password:"tutu"}]);
}
};
};
I've modified my main.js by adding this, just before the routes :
require('./models')(app);
The question is, I don't know how to modify my routes/user.js to call this model !
I would like to have something like this in routes/users.js :
module.exports = function(app) {
const Users = app.models.users; // not working here : TypeError: Cannot read property 'users' of undefined
app.get('/users', function(req, res) {
Users.findAll({}, function(users) {
res.json({users: users});
});
});
};
How can I use my model via the app var ?
note : I found a solution with a module called "config" for dependencies injections, but I'd rather use simple coding before using such powerfull shortcuts.
Any help appreciated ! Thanks !
Upvotes: 0
Views: 319
Reputation: 7736
If you want to access models
you need to define it as a property on app
That's the job of models.js
, I would say. You are passing app to models.js
but not changing it at all.
I would recommend changing models.js
to be more like this:
module.exports = function(app) {
app.models = {
users : // import db and return users so routes can avail of them
};
};
Upvotes: 1