Search code examples
node.jsapiredishapi

Build API with redis and hapi


I am trying to send the results of a get from redis via hapi, but i just keep getting a 500. How can I send the result from the redis get to the client. Code and error below.

Error

Debug: internal, implementation, error

Error: handler method did not return a value, a promise, or throw an error

{
    statusCode: 500,
    error: "Internal Server Error",
    message: "An internal server error occurred"
}

Code

'use strict';
const Hapi = require('@hapi/hapi');
const redis = require("redis");
const client = redis.createClient();

client.on("error", function (error) {
  console.error(error);
});

const init = async () => {

  const server = Hapi.server({
    port: 3001,
    host: 'localhost'
  });

  server.route({
    method: 'GET',
    path: '/api/v1/key/{id}',
    handler: (request, h) => {
      client.get(request.params.id, (err, res) => {
        if (err) {
          h.response(err)
        } else {
          h.response(res)
        }
      });
    }
  });

  await server.start();
  console.log('Server running on %s', server.info.uri);
};

process.on('unhandledRejection', (err) => {

  console.log(err);
  process.exit(1);
});

init();

Solution

  • I figured it out. You can convert the redis module to a promise and return values from there.

    'use strict';
    const Hapi = require('@hapi/hapi');
    const redis = require('redis');
    const client = redis.createClient();
    const { promisify } = require("util");
    const getAsync = promisify(client.get).bind(client);
    const setAsync = promisify(client.set).bind(client);
    
    client.on("error", function (error) {
        console.error(error);
    });
    
    const init = async () => {
    
        const server = Hapi.server({
            port: 5000,
            host: 'localhost'
        });
    
        server.route({
            method: 'GET',
            path: '/api/v1/key/{id}',
            handler: (req, h) => {
                return getAsync(req.params.id).then(res => {
                    console.log(res)
                    return res
                }).catch(err => {
                    console.error(err)
                    return err
                });
            }
    
        })
    
        server.route({
            method: 'post',
            path: '/api/v1/key',
            handler: (req, h) => {
                return setAsync(req.payload.hash, req.payload.key).then(res => {
                    console.log(res)
                    return res
                }).catch(err => {
                    console.error(err)
                    return err
                })
            }
    
        })
    
        await server.start();
        console.log('Server running on %s', server.info.uri);
    };
    
    process.on('unhandledRejection', (err) => {
    
        console.log(err);
        process.exit(1);
    });
    
    init();