How can I write Node.js web services in a dry way?

I am writing a bunch of web services that have common patterns. For example, they all have the same meaning.

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 a way to write the above in one common place, so if something changes, can I make one change, not five or six?

+4
source share
1 answer

That's right. You can create a module that will return a basic http server that implements settings / methods common to all of your services. From there, you can simply require this module and add additional maintenance methods.

The module will look something like this:

 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 as follows:

 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 elements from the module, you can easily do this to make them available in the service implementation files.

+2
source

Source: https://habr.com/ru/post/1412873/


All Articles