当前位置: 动力学知识库 > 问答 > 编程问答 >

node.js - Express.js database and validation logic. Where?

问题描述:

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 :)

分享给朋友:
您可能感兴趣的文章:
随机阅读: