hapi.dev icon indicating copy to clipboard operation
hapi.dev copied to clipboard

Fixed Express Migration Tutorial.

Open DanielNoamTuby opened this issue 1 year ago • 0 comments
trafficstars

In Express Migration Tutorial -> Loading a plugin -> Options there was a mix between the express and hapi examples.

Original:

Options

You can add options to Express middleware by exporting a function that accepts an options parameter, which then returns the middleware. In hapi, you set the options when you register the plugin. Lets have a look:

Express:

module.exports = function (options) {
    return function getDate(req, res, next) {

        req.getDate = function() {

            const date = 'Hello ' + options.name + ', the date is ' + new Date();
            return date;
        };

        next()
    };
};

hapi:

server.register({
    plugin: getDate,
    options: {
        name: 'Tom'
    }
})

To get access to the options in hapi, you simply refer to the options object when you create the plugin:

Express:

const getDate = require('./mw/getDate.js');

app.use(getDate({ name: 'Tom' }));

hapi:

const getDate = {
    name: 'getDate',
    version: '1.0.0',
    register: async function (server, options) {

        const currentDate = function() {

            const date = 'Hello ' + options.name + ', the date is ' + new Date();
            return date;
        };

        server.decorate('toolkit', 'getDate', currentDate);
    }
};

Fixed:

Options

You can add options to Express middleware by exporting a function that accepts an options parameter, which then returns the middleware. In hapi, you set the options when you register the plugin. Lets have a look:

Express:

module.exports = function (options) {
    return function getDate(req, res, next) {

        req.getDate = function() {

            const date = 'Hello ' + options.name + ', the date is ' + new Date();
            return date;
        };

        next()
    };
};

hapi:

const getDate = {
    name: 'getDate',
    version: '1.0.0',
    register: async function (server, options) {

        const currentDate = function() {

            const date = 'Hello ' + options.name + ', the date is ' + new Date();
            return date;
        };

        server.decorate('toolkit', 'getDate', currentDate);
    }
};

To get access to the options in hapi, you simply refer to the options object when you create the plugin:

Express:

const getDate = require('./mw/getDate.js');

app.use(getDate({ name: 'Tom' }));

hapi:

server.register({
    plugin: getDate,
    options: {
        name: 'Tom'
    }
})

DanielNoamTuby avatar Jun 14 '24 11:06 DanielNoamTuby