Skip to content

Latest commit

 

History

History
154 lines (130 loc) · 3.3 KB

README.md

File metadata and controls

154 lines (130 loc) · 3.3 KB

hapi-hemera

Build Status NPM Downloads npm js-standard-style

hapi-hemera is a Hemera micro-services plugin for Hapi 17+. The plugin integrates the Hemera functionality into hapi.

Plugin Registration

const server = new Hapi.Server()
await server.register({
  plugin: require('hapi-hemera'),
  options: {
    hemera: {
      name: 'test',
      logLevel: 'info'
    },
    nats: 'nats://localhost:4242',
    // If you want to add hemera plugins
    plugins: [require('hemera-joi')]
  }
})

Plugin registration with a custom Hemera instance

const server = new Hapi.Server()
const hemeraInstance = new Hemera()
await server.register({
  plugin: require('hapi-hemera'),
  options: {
    hemeraInstance: hemeraInstance,
    nats: 'nats://localhost:4242'
  }
})

Use toolkit decorator

server.route({
  method: 'POST',
  path: '/add',
  handler: function (request, h) {
    return h.hemera().act({ topic: 'math', cmd: 'add', a: 2, b: 2 })
  }
}

Use server decorator

server.route({
  method: 'POST',
  path: '/add',
  handler: async function (request, h) {
    let resp = await server.hemera.act({ topic: 'math', cmd: 'add', a: 2, b: 2 })
    // access result
    resp.data
    // retain parent context
    resp = resp.context.act(...)
  }
}

Use request decorator

server.route({
  method: 'POST',
  path: '/add',
  handler: function (request, h) {
    return request.hemera.act({ topic: 'math', cmd: 'add', a: 2, b: 2 })
  }
}

Server methods

server.action('generate', {
  topic: 'generator',
  cmd: 'id'
})
const result = await server.methods.generate()

Use handler decorator and accept params, query and payload as pattern

server.route({
  method: 'GET',
  path: '/api/add',
  handler: {
    hemera: {
      pattern: {
        topic: 'math',
        cmd: 'add'
      }
    }
  }
})

Gracefully shutdown

We hook into Hapi onPostStop event to gracefully shutdown hemera.

Enrich pattern with contextual data

server.register({
    plugin: HapiHemera,
    options: {
      basePattern: function (request) {
        return {
          trace$: {
            traceId: request.headers['x-request-id']
          }
        }
      },
      nats: {
        url: noAuthUrl
      }
    }
})

// The basePattern is merged with the pattern
hemera.act({ a: 1 })

// Results in following pattern
 { a: 1, trace$: { traceId: 123 } }
basePattern: function(request) {
  return {
    trace$: {
      traceId: request.plugins.zipkin.traceId.traceId,
      spanId: request.plugins.zipkin.traceId.spanId,
      sampled: request.plugins.zipkin.traceId.sampled,
      flags: request.plugins.zipkin.traceId.flags
    }
  }
}