event-schema
v1.0.1
Published
A simple library for defining event schemas, validating published events, and subscribing to events.
Downloads
2
Readme
event-schema
Validates event payloads by attaching a JSON schema to each event topic.
Example
const EventSchema = require('event-schema')
const es = new EventSchema()
// define a topic and what the event payload must look like
es.define('topicX', {
type: 'object',
properties: {
name: {
type: 'string',
minLength: 1
},
age: {
type: 'integer',
minimum: 0
}
}
})
// subscribe a handler to the event
es.on('topicX', function (payload) {
console.log(payload)
})
// emit an event to the topic
es.emit('topicX', {
name: 'Bob',
age: 20
})
Create EventSchema instance
Each event-schema instance manages its own topics, handlers, and emitted events.
const EventSchema = require('event-schema')
const es = new EventSchema()
Define a JSON Schema to use for a Specific Topic
es.define('topicX', {
type: 'string',
minLength: 1
})
Subscribe to an Event Topic
es.on('topicX', function (payload) {
// add code to handle the event payload here
})
Unsubscribe from an Event Topic
function handler (payload) {
// add code to handle the event payload here
}
// add an event handler first
es.on('topicX', handler)
// remove the handler
es.off('topicX', handler)
Subscribe to a Single Event on a Topic
es.once('topicX', function handler (payload) {
// this code will only run for the first event on this topic
})