postie-mediator

    1.1.0 • Public • Published

    Postie

    Build Status

    A module for handling in-process messages (commands, queries and events) within an app.

    Installation

    npm install postie-mediator

    Importing into your project

    Postie's constructor is the default export of its module, which means that importing it via CommonJS differs slightly from the norm:

    const Postie = require("postie-mediator").default;

    Importing via ES6 syntax:

    import Postie from 'postie-mediator';

    Working with Postie

    Postie's API is rather simple with just two methods. See below for usage details.

    Registering message handlers

    To register message handlers, simply provide the constructor function of the desired message type and one or more handlers that implement the message handler interface, or a factory that produces handlers:

    interface MessageHandler {
      handle(message);
    }
    
    // Greet command
    class Greet {
      constructor(name){
        this.name = name;
      }
    }
    
    // Command handler (can also be an object that implements the MessageHandler interface)
    class Greeter {
      handle(message){
        console.log(message.name);
      }
    }
    
    const postie = new Postie();
    
    // Standard argument passing
    postie.register(Greet, new Greeter());
    
    // or handlers in an array
    postie.register(Greet, [ new Greeter() ]);
    
    // or a handler factory
    postie.register(Greet, () => new Greeter());
    

    Sending a message

    To send a message, create an instance of a previously registered message type and dispatch it to Postie. When sending a message, a promise is returned to account for async. work within handlers; it resolves to an array of handler responses.

    class Message {}
    
    const handler = {
      handle(message) {
        return 'Message handled';
      }
    };
    
    postie.register(Message, handler);
    
    const message = new Message();
    
    const continuation = postie.send(message);
    
    continuation.then(responses => // responses => [ 'Message handled' ]);
    

    You're not a puppet

    Using this module should allow you to work in whichever way you wish, without a prescribed methodology pulling on your strings. For example, while it makes sense for a command/query to only be processed by a single handler, you are free to register as many handlers as you wish for each message type.

    The same goes for events too: typically they are the only type of message that can have multiple handlers. While publishing an event is more semantic than sending an event, a publish method would only be an alias for the send method, hence its omission from the API.

    Install

    npm i postie-mediator

    DownloadsWeekly Downloads

    0

    Version

    1.1.0

    License

    MIT

    Unpacked Size

    32.7 kB

    Total Files

    10

    Last publish

    Collaborators

    • jshuttler