HapiJS configuration for endpoint caching with @hapi/catbox-redis

36 views Asked by At

Objective: Implementing redis cache in a hapi server's endpoint.

Current situation: The connection to redis has been proven correct, since the Client is active in the Redis local browser. However, when making a GET request to the endpoint, the caching behaviour is missing (it is going into the handler every time). It doesn't show errors, it doesn't create a key in the Redis database.

Expected behavior: On the first request: Wait for one second, then return a numeric date. On n amount of requests during the next 3 minutes, return the cached request from redis instantly, without accessing the endpoint.

Is there anything I am missing on this server / route config?

Thanks:

import * as Hapi from '@hapi/hapi';
import * as CatBoxRedis from '@hapi/catbox-redis';

const start = async () => {
    const server = Hapi.server({
        port: 3456,
        cache: [{
            name: 'my_cache',
            provider: {
                constructor: CatBoxRedis.Engine,
                options: {
                    partition: 'partitionTest',
                    host: '127.0.0.1',
                    port: 6379,
                },
            },

        }]
    });

    server.route({
        path: '/test',
        method: 'GET',
        options: {
            cache: {
                expiresIn: 3 * 60 * 1000,
                privacy: 'private',
                statuses: [200],
            },
        },
        handler: async function (request, h) {
            await new Promise(r => setTimeout(r, 1000));
            return h.response({ date: Number(new Date()) }).code(200);
        },
    });

    await server.initialize();
    await server.start();
    console.log('Server running at:', server.info.uri);
};

start();

process.on('unhandledRejection', (error) => {
    console.log('Unhandledrejection => ', error)
})
0

There are 0 answers