1
\$\begingroup\$

I have made a RESTful API built with Node.js, Express, Basic-auth and Mongoose. it will respond JSON.

This is the folder structure:

.
├── index.js
├── lib
│   ├── middleware
│   │   ├── Authentication.js
│   │   └── index.js
│   ├── routes
│   │   ├── Account.js
│   │   └── index.js
│   └── schemas
│       └── Account.js
├── node_modules

This is the planned endpoint:

        URI         |          GET             |     POST       |            PUT               |    DELETE
-------------------------------------------------------------------------------------------------------------------
/account            | Get all document         | Add a document |              -               |          -
/account/:id        | Get a document           |       -        | Update a document            | Delete a document

index.js

var app = require('express')();
var logger = require('morgan');
var bodyParser = require('body-parser');
var middleware = require('./lib/middleware');
var routes = require('./lib/routes');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(middleware.Authentication);

app.post('/account', routes.insertAccount);
app.get('/account', routes.getAccounts);
app.get('/account/:id', routes.getAccountById);
app.put('/account/:id', routes.updateAccountById);
app.delete('/account/:id', routes.deleteAccountById);

app.listen(8000), function(){
    console.log('Server starts on http://localhost:8000');
};

The middleware Authentication.js:

var auth = require('basic-auth');

module.exports.Authentication = function(req, res, next){
    var credentials = auth(req);
    if (!credentials ||
        credentials.name !== 'admin' ||
        credentials.pass !== 'rahasia'){
        return res.status(401).json({status: 'login required'});
    }

    next();
}

The middleware index.js:

module.exports = require('./Authentication');

The routes Account.js:

var mongoose = require('mongoose');
var accountSchema = require('../schemas/Account')
var Account = mongoose.model('Account', accountSchema);

mongoose.connect('mongodb://localhost:27017/account');

module.exports.getAccounts = function(req, res){
    var query = Account.find({});
    query.exec(function(err, docs){
        if (err) return console.error(err);

        res.json(docs);
    });
}

module.exports.getAccountById = function(req, res){
    var query = Account.findById(req.params.id);
    query.exec(function(err, doc){
        if (err) {
            res.status(500)
                .json({
                    task: 'get one account',
                    param: req.params.id,
                    status: 'fail',
                    error: err
                });

            return console.error(err);
        }

        if (doc === null) {
            return res.json({
                task: 'get one account',
                param: req.params.id,
                status: 'Not found'
            });
        }

        res.json(doc);
    });
}

module.exports.updateAccountById = function(req, res){
    var query = Account.findByIdAndUpdate(req.params.id, req.body);
    query.exec(function(err, raw){
        if (err) return console.error(err);

        if (raw === null) {
            return res.status(500)
                .json({
                    task: 'update',
                    status: 'fail'
                });
        }

        res.json({
            task: 'update',
            param: req.body,
            status: 'ok',
            data: raw
        });
    });
}

module.exports.insertAccount = function(req, res){
    var query = Account.create(req.body, function(err, doc){
        if (err) {
            res.status(500)
                .json({
                    task: 'insert',
                    status: 'fail',
                    error: err
                });

            return console.error(err);
        }

        res.json({
            task: 'insert',
            status: 'ok',
            data: doc
        });
    });
}

module.exports.deleteAccountById = function(req, res){
    var query = Account.findByIdAndRemove(req.params.id);
    query.exec(function(err, doc){
        if (err) {
            res.status(500)
                .json({
                    task: 'delete',
                    id: req.params.id,
                    status: 'fail',
                    error: err
                });

            return console.error(err);
        }

        if (doc === null) {
            return res.status(500)
                    .json({
                        task: 'delete',
                        id: req.params.id,
                        status: 'fail'
                    });
        }

        res.json({
            task: 'delete',
            status: 'ok',
            removed: doc
        });
    });
}

The routes index.js:

module.exports = require('./Account');

The schemas Account.js:

var mongoose = require('mongoose');
var validator = require('validator');
var Schema = mongoose.Schema;

var accountSchema = new Schema({
    name: {
        type: String,
        required: [true, 'Nama wajib diisi.']
    },
    title: String,
    email: {
        type: String,
        lowercase: true,
        required: [true, 'Email wajib diisi.'],
        unique: true,
        validate: {
            validator: function(value){
                return validator.isEmail(value);
            },
            message: '{VALUE} Bukan email yang sah.'
        }
    },
    phone: Number,
    address: {
        type: String,
        text: true
    },
    company: {
        type: String,
        text: true
    }
});

module.exports = accountSchema;
\$\endgroup\$
1
\$\begingroup\$

I've just few suggestions

  1. Split your database access logic into dao, and since you're using mongoose you can write static or instance methods on top of your schema.

  2. For authentication i would suggest you have a look at passport.js they have many strategies which you can implement basic,bearer,openId etc, if you need an example let me know.

  3. Try using promises instead of callbacks, mongoose already supports promises will help you in writing more manageable code.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.