Modular express application

suggest change

To make express web application modular use router factories:

Module:

// greet.js
const express = require('express');

module.exports = function(options = {}) { // Router factory
    const router = express.Router();

    router.get('/greet', (req, res, next) => {
        res.end(options.greeting);
    });

    return router;
};

Application:

// app.js
const express = require('express');
const greetMiddleware = require('./greet.js');

express()
    .use('/api/v1/', greetMiddleware({ greeting:'Hello world' }))
    .listen(8080);

This will make your application modular, customisable and your code reusable.

When accessing http://<hostname>:8080/api/v1/greet the output will be Hello world

More complicated example

Example with services that shows middleware factory advantages.

Module:

// greet.js
const express = require('express');

module.exports = function(options = {}) { // Router factory
    const router = express.Router();
    // Get controller
    const {service} = options;

    router.get('/greet', (req, res, next) => {
        res.end(
            service.createGreeting(req.query.name || 'Stranger')
        );
    });

    return router;
};

Application:

// app.js
const express = require('express');
const greetMiddleware = require('./greet.js');

class GreetingService {
    constructor(greeting = 'Hello') {
        this.greeting = greeting;
    }

    createGreeting(name) {
        return `${this.greeting}, ${name}!`;
    }
}

express()
    .use('/api/v1/service1', greetMiddleware({
        service: new GreetingService('Hello'),
    }))
    .use('/api/v1/service2', greetMiddleware({
        service: new GreetingService('Hi'),
    }))
    .listen(8080);

When accessing http://<hostname>:8080/api/v1/service1/greet?name=World the output will be Hello, World and accessing http://<hostname>:8080/api/v1/service2/greet?name=World the output will be Hi, World.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents