3

Nothing important
My first question here on stackoverflow. I've used it for years to find answers, but now I need a bit of guidance. I'm new to node and express and the async way of structuring an app.

Goal - A REST interface with validation and neDB database
I got the following code working. POST a new user is the only route. It's based on many answers and tuts mixed together. I find it hard to scaffold out the logic, to get a structure you can build on.

I'm not sure at all whether this structure is crap or not. Any advice would be appreciated.

Main file is initializing the database, middleware validator, and starting the app.

// rest.js
var express    = require('express'),
    bodyParser = require('body-parser'),
    validator  = require('express-validator'),

    db         = require('./database/db'),
    userRouter = require('./routers/users');

db.init();

var app = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(validator());

app.use('/api/users', userRouter);

var port = process.env.PORT || 8080; 
app.listen(port);

Database
This question/answer made me create the small database module with alterations. How do you pass objects around node express application?
It doesn't have much attention. Maybe because it's very obvious or maybe not a good answer.

The idea is that whem i get multiple collections, they all get initialized on startup, but I can request a single collection if that's all the module needs, or I can get the entire db object back if another module would require that.

// database/db.js

var nedb       = require('nedb');

var db = {};

db.init = function() {
    db.users = new nedb({ filename: './database/data/users', autoload: true });
    db.users.ensureIndex({ fieldName: 'username', unique: true }, function (err) {});
    db.users.ensureIndex({ fieldName: 'email', unique: true }, function (err) {});
};

db.get = function(collection) {
    if (collection && db[collection])
        return db[collection];
    return db;
}

module.exports = db;

Router
I require the User Model here and use the express-validator and sanitizes the request before passing it on to the model, based on a minimalist key schema in the model. I don't have any controllers. If I had (or when I do), I would put the validation there. The router is supposed to send the response and status right?

// routers/users.js

var express    = require('express'),
    _          = require('lodash'),
    User       = require('../models/user');

var userRouter = express.Router();

userRouter.route('/')
    .post(function(req, res) {

        req.checkBody('username', 'Username must be 3-20 chars').len(3,20);
        req.checkBody('email', 'Not valid email').isEmail();
        req.checkBody('password', 'Password must be 6-20 chars').len(6,20);

        var err = req.validationErrors();
        if (err) {
            res.status(422).send(err);
            return;
        }

        var data = _.pick(req.body, _.keys(User.schema));

        User.create(data, function (err, newData) {
            if (err) {
                res.status(409).send(err);
            } else {
                res.status(201).send(newData);
            }
        });

    });

module.exports = userRouter;

Model
The model requires the database module and gets the "connection". Is this OK?

// models/user.js
var db          = require('../database/db');

var User = function (data) {
    this.data = data;
};

User.schema = {
    _id: null,
    username: null,
    email: null,
    password: null
};

User.create = function (data, callback) {
    db.get('users').insert(data, callback);
};

module.exports = User;

Thanks for reading this far. Now, my question is: Is there something fundamentally wrong with this setup, concerning the database usage and the validation logic. I know the model looks stupid :)

2
  • Welcome to Stack Overflow write mode! I voted to close your question because you seem to be inviting a lengthy subjective discussion as opposed to a concise answer to a specific problem (which is what SO is intended for). stackoverflow.com/help/asking Jun 7, 2015 at 17:24
  • Thanks Andrew, and sorry my question became to non-specific.
    – Simon Says
    Jun 7, 2015 at 18:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.