@fakehost/exchange

中文文档
1.0.0-beta.2发布于 2023/10/04MITTypeScriptESM + CJS近 30 天下载 2.3万

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

原始使用文档
文档目录6 节
  1. Overview
  2. Example Usage
  3. Protocol Handler
  4. Debug
  5. License
  6. Migrating from v0.x

@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

版本与发布记录

@fakehost/exchange 共发布 28 个版本,首次发布于 2021/09/02;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.0.0-beta.2latest2023/10/043 年前
1.0.0-beta.12023/10/023 年前
1.0.0-beta.0beta2023/08/073 年前
0.2.1canary2023/04/203 年前
0.2.02023/01/303 年前
0.1.1-alpha.62022/10/254 年前

关于 @fakehost/exchange 的常见问题

@fakehost/exchange 是什么?

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

如何安装 @fakehost/exchange?

在项目目录运行 npm install @fakehost/exchange,或使用 pnpm add / yarn add / bun add。

@fakehost/exchange 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@fakehost/exchange 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@fakehost/exchange 可以商用吗?

@fakehost/exchange 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@fakehost/exchange 的下载量有多少?

根据 npm 官方下载统计,@fakehost/exchange 在 2026/10/14 – 2026/11/12 这 30 天内被下载 23,364 次,日均约 779 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@fakehost/exchange 还在维护吗?

最新版本 1.0.0-beta.2 发布于 2023/10/04(3 年前);至今共发布 28 个版本,其中过去 12 个月发布了 0 个;首次发布于 2021/09/02。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。