1.0.0-beta.2 • Published 7 months ago

@fakehost/exchange v1.0.0-beta.2

Weekly downloads
-
License
MIT
Repository
-
Last release
7 months ago

@fakehost/exchange

NPM Version

Overview

See the docs for more info.

A basic package for building fake messaging services that communicate over websockets. Can run as a nodejs service, or be bundled inside the browser.

This library won't give you much on its own. Instead its used to support running the same fake service code hosted within the browser or running as a node process.

Provides two main objects:

  • WsHost. For starting a websocket service. This runs as a node process which can be started from the command line, or started from nodejs tests e.g. jest, vitest, playwright, webdriver etc.
  • BrowserWsHost. For starting a "mocked" websocket service. This runs directly within the browser, and is useful for bundling "fake" services within Storybook, or a demo application, and for running browser based tests such as Cypress.

⚠️ Don't use this in production environments. This is for testing, and demo purposes only.

Example Usage

For a full example see @fakehost/fake-signalr.

Protocol Handler

Messaging services have many different types of protocols to manage the exchange of messages. Many of these are custom.

Lets say we are building a fake protocol handler for a service that has the following incoming message and outgoing message structure:

type IncomingMessage = {
    destination: string
    payload: unknown
}

type OutgoingMessage = {
    destination: string
    payload: unknown
}

Messages are all in JSON, so we can easily inspect what the service is doing by examining the network tab and looking at the messages.

An extremely basic protocol that only supports simple request/response messages could look like:

import { Host, ConnectionId, Connection, ExchangeEvent } from '@fakehost/exchange'

type MessageHandler = (payload: unknown) => unknown

export class MyProtocolHandler {

    private messageHandlers = new Map<string, MessageHandler>()

    constructor(host: Host) {
        host.on('connection', this.onConnection.bind(this))
        host.on('disconnection', this.onDisconnection.bind(this))
        host.on('message', this.onMessage.bind(this))
    }

    onConnection({ connection }: ExchangeEvent<'connection'>) {
        console.log(`a new connection "${connection.id}"`)
    }

    onDisconnection({ connection }: ExchangeEvent<'disconnect'>) {
        console.log(`connection "${connection.id}" has disconnected`)
    }

    onMessage({ connection, message: rawMessage }: ExchangeEvent<'message'>) {
        // deserialize the incoming message
        const message: IncomingMessage = this.deserialize(rawMessage)

        // get the handler for the service + method
        const handler = this.messageHandlers.get(message.destination)

        if(!handler) {
            console.log(`"${destination}" not handled`)
            return
        }

        // call the handler
        const result = handler(message.payload)

        // send the handler's response
        connection.write(JSON.stringify({
            destination: message.destination,
            payload: result
        }))
    }

    deserialize(message: string | Buffer) {
        const parsed = typeof message === 'string' ? message : new TextDecoder('utf-8').decode(message);
        return JSON.parse(parsed) as IncomingMessage;
    }

    register(destination: string, handler: MessageHandler) {
        this.messageHandlers.set(destination, handler)
    }
}

And lets wire up a handler, and start MyProtocolHandler running as a localhost service:

import { WsHost } from '@fakehost/exchange'

// start a websocket service listening on port 5000 at /json
const host = new WsHost({
    name: 'fake',
    debug: true,
    port: 5000,
    path: '/json'
})

// create a new protocol handler
const protocol = new MyProtocolHandler(host)

// create a simple handler and register it to handle incoming messages with destination of `greeting`
const greetingHandler = (payload: { name: string }) => {
    return `Hello, ${name}!`
}
protocol.register('greeting', greetingHandler)

Debug

Debug logging can be enabled through the constructors, or via the environment variable:

DEBUG=@fakehost/exchange

License

@fakehost/exchange is licensed under the MIT License.

Migrating from v0.x

See Migrating from v0.x

1.0.0-beta.2

7 months ago

1.0.0-beta.0

9 months ago

1.0.0-beta.1

7 months ago

0.2.1

1 year ago

0.2.0

1 year ago

0.1.1-alpha.3

2 years ago

0.1.1-alpha.6

2 years ago

0.1.1-alpha.5

2 years ago

0.0.20

2 years ago

0.0.19

2 years ago

0.0.14

2 years ago

0.0.15

2 years ago

0.0.16

2 years ago

0.0.17

2 years ago

0.0.18

2 years ago

0.0.10

3 years ago

0.0.11

3 years ago

0.0.12

3 years ago

0.0.13

3 years ago

0.0.9

3 years ago

0.0.8

3 years ago

0.0.5

3 years ago

0.0.7

3 years ago

0.0.6

3 years ago

0.0.4

3 years ago

0.0.3

3 years ago

0.0.2

3 years ago

0.0.1

3 years ago