hapi-hemera is a Hemera micro-services plugin for Hapi 17+. The plugin integrates the Hemera functionality into hapi.
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')]
}
})
const server = new Hapi.Server()
const hemeraInstance = new Hemera()
await server.register({
plugin: require('hapi-hemera'),
options: {
hemeraInstance: hemeraInstance,
nats: 'nats://localhost:4242'
}
})
server.route({
method: 'POST',
path: '/add',
handler: function (request, h) {
return h.hemera().act({ topic: 'math', cmd: 'add', a: 2, b: 2 })
}
}
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(...)
}
}
server.route({
method: 'POST',
path: '/add',
handler: function (request, h) {
return request.hemera.act({ topic: 'math', cmd: 'add', a: 2, b: 2 })
}
}
server.action('generate', {
topic: 'generator',
cmd: 'id'
})
const result = await server.methods.generate()
server.route({
method: 'GET',
path: '/api/add',
handler: {
hemera: {
pattern: {
topic: 'math',
cmd: 'add'
}
}
}
})
We hook into Hapi onPostStop
event to gracefully shutdown hemera.
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 } }
Example for zipkin-instrumentation-hapi
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
}
}
}