hapijs / hapi.dev

The hapi.dev developer portal
53 stars 68 forks source link

Fixed Express Migration Tutorial. #540

Open DanielNoamTuby opened 3 months ago

DanielNoamTuby commented 3 months ago

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'
    }
})