Categories
Hapi

Server-Side Development with Hapi.js — MIME Types and Events

Spread the love

Hapi.js is a small Node framework for developing back end web apps.

In this article, we’ll look at how to create back end apps with Hapi.js.

MIME Types

We can get information about various MIME types with the modules.

For instance, we can write:

const Hapi = require('@hapi/hapi');
const Mimos = require('@hapi/mimos');

const options = {
  override: {
    'node/module': {
      source: 'iana',
      compressible: true,
      extensions: ['node', 'module', 'npm'],
      type: 'node/module'
    },
    'application/javascript': {
      source: 'iana',
      charset: 'UTF-8',
      compressible: true,
      extensions: ['js', 'javascript'],
      type: 'text/javascript'
    },
    'text/html': {
      predicate(mime) {
        mime.foo = 'test';
        return mime;
      }
    }
  }
}

const mimos = new Mimos(options);

const init = async () => {
  const server = new Hapi.Server({
    port: 3000,
    host: '0.0.0.0'
  });

  server.route({
    method: 'GET',
    path: '/',
    config: {
      handler(request, h) {
        return mimos.type('text/html');
      },
    }
  });

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

process.on('unhandledRejection', (err) => {
  console.log(err);
  process.exit(1);
});
init();

We add the options object with the override property to set the data for the given MIME types.

Then we call mimos.type with the MIME type we want to look up.

And then we get:

{"source":"iana","compressible":true,"extensions":["html","htm","shtml"],"type":"text/html","foo":"test"}

as the returned value.

Collect Server Ops Data

We can collect server ops data easily with the @hapi/oppsy module.

To use it, we can write:

const Hapi = require('@hapi/hapi');
const Oppsy = require('@hapi/oppsy');

const init = async () => {
  const server = new Hapi.Server({
    port: 3000,
    host: '0.0.0.0'
  });

  const oppsy = new Oppsy(server);
  oppsy.on('ops', (data) => {
    console.log(data);
  });

  server.route({
    method: 'GET',
    path: '/',
    config: {
      handler(request, h) {
        return 'hello'
      },
    }
  });

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

process.on('unhandledRejection', (err) => {
  console.log(err);
  process.exit(1);
});
init();

We create the oppsy object with the Oppsy constructor.

Then we listen to the ops event with the oppsy.on method.

And in the event handler, we log the data from the server.

It includes data like requests, CPU usage, response times, memory usage, and more.

Events

We can create our own event bus with the @hapi/podium module.

For example, we can write:

const Hapi = require('@hapi/hapi');
const Podium = require('@hapi/podium');

const emitter = new Podium()
const context = { count: 0 }

emitter.registerEvent({
  name: 'event',
  channels: ['ch1', 'ch2']
})

const handler1 = function () {
  ++this.count
  console.log(this.count)
};

const handler2 = function () {
  this.count = this.count + 2
  console.log(this.count)
}

emitter.on({
  name: 'event',
  channels: ['ch1']
}, handler1, context);

emitter.on({
  name: 'event',
  channels: ['ch2']
}, handler2, context)

emitter.emit({
  name: 'event',
  channel: 'ch1'
})

emitter.emit({
  name: 'event',
  channel: 'ch2'
})

emitter.hasListeners('event')
emitter.removeAllListeners('event')
const init = async () => {
  const server = new Hapi.Server({
    port: 3000,
    host: '0.0.0.0'
  });

  server.route({
    method: 'GET',
    path: '/',
    config: {
      handler(request, h) {
        return 'hello'
      },
    }
  });

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

process.on('unhandledRejection', (err) => {
  console.log(err);
  process.exit(1);
});
init();

We import the module, then we create the emitter object with it.

Then we register events with the emitter.registerEvent method.

We can separate events into their own channels.

context is the value of this in the event handlers.

So this.count will be updated and logged within the event handlers.

Conclusion

We can create our own event bus with @hapi/podium and handle MIME types with the @hapi/mimos module.

Leave a Reply

Your email address will not be published. Required fields are marked *