deltanovember
deltanovember

Reputation: 44061

How can I write Node.js web services in a DRY manner?

I'm writing a bunch of web services which all share some common patterns. For example they all share the same requires

var x = require(...);
var y = require(...);

do similar authentication

var auth = express.basicAuth(...);
server.use(auth); 

and have similar error messages.

server.error(function(err, req, res, next){
    ...
});

Is there some way of writing the above in one common place so that if anything changes I can make a single change rather than five or six?

Upvotes: 4

Views: 605

Answers (1)

Timothy Strimple
Timothy Strimple

Reputation: 23070

Absolutely. You can create a module which will return a base http server which implements the settings / methods that are common to all of your services. From there you can just require that module, and add additional service methods do it.

The module would look something like:

var express = require('express');
var app = express.createServer();

//  Configure

//  Common Functionality
app.error(function(err, req, res, next){
    ...
});

exports.app = app;

And then you can use this module like so:

var service = require('./service-base').app;

service.get('/users', function(req, res) {
    //  get and return users
});

service.listen(1234);

If you need to expose other items from the module you can easily do that to make them available in the service implementation files as well.

Upvotes: 2

Related Questions