@adonisjs/transmit-client

中文文档
1.1.0发布于 2026/01/18MITTypeScriptES Module零依赖构建来源已验证近 30 天下载 6.4万

A client for the native Server-Sent-Event module of AdonisJS.

原始使用文档
文档目录10 节
  1. Usage | Checkout AdonisJS
  2. Table of Contents
  3. Installation
  4. Usage
  5. Creating a subscription
  6. Unsubscribing
  7. Subscription Request
  8. Authenticated event stream
  9. Custom UID Generator
  10. Reconnecting

AdonisJS Transmit Client

A client for the native Server-Sent-Event (SSE) module of AdonisJS.


typescript-image gh-workflow-image npm-image npm-download-image license-image



AdonisJS Transmit Client is a client for the native Server-Sent-Event (SSE) module of AdonisJS. It is built on top of the EventSource API and provides a simple API to receive events from the server.

Table of Contents

Installation

Install the package from the npm registry as follows:

npm i @adonisjs/transmit-client

Usage

The module exposes a Transmit class, which can be used to connect to the server and listen for events.

import { Transmit } from '@adonisjs/transmit-client'

const transmit = new Transmit({
  baseUrl: 'http://localhost:3333',
})

Creating a subscription

The subscription method is used to create a subscription to a channel. The method accepts the channel name

const subscription = transmit.subscription('chat/1')

Then, you have to call the create method on the subscription to register it on the backend.

await subscription.create()

You can listen for events on the channel using the onMessage method. You can define as many listeners as you want on the same subscription.

subscription.onMessage((message) => {
  console.log(message)
})

You can also listen only once for a message using the onMessagetOnce method.

subscription.onMessageOnce((message) => {
  console.log('I will be called only once')
})

Note listeners are local only; you can add them before or after registering your subscription on the server.

Unsubscribing

The onMessage method returns a function to remove the message handler from the subscription.

const unsubscribe = subscription.onMessage(() => {
  console.log('message received!')
})

// later
unsubscribe()

If you want to entirely remove the subscription from the server, you can call the delete method.

await subscription.delete()

Subscription Request

You can alter the subscription request by using the beforeSubscribe or beforeUnsubscribe options.

const transmit = new Transmit({
  baseUrl: 'http://localhost:3333',
  beforeSubscribe: (_request: Request) => {
    console.log('beforeSubscribe')
  },
  beforeUnsubscribe: (_request: Request) => {
    console.log('beforeUnsubscribe')
  },
})

Authenticated event stream

The __transmit/events stream is opened using EventSource, which cannot send custom headers. That means beforeSubscribe/beforeUnsubscribe only affect the subscribe/unsubscribe HTTP calls. If you rely on header-based auth, protect __transmit/subscribe and __transmit/unsubscribe, or provide a custom eventSourceFactory that can send headers.

Example using @microsoft/fetch-event-source:

import { fetchEventSource } from '@microsoft/fetch-event-source'

function createFetchEventSource(
  url: string | URL,
  options: { withCredentials: boolean },
  headers: Record<string, string>
) {
  const controller = new AbortController()
  const listeners = new Map<string, Set<(event: MessageEvent) => void>>()

  const dispatch = (type: string, data?: string) => {
    const event = new MessageEvent(type, { data })
    listeners.get(type)?.forEach((listener) => listener(event))
  }

  fetchEventSource(url.toString(), {
    headers,
    credentials: options.withCredentials ? 'include' : 'omit',
    signal: controller.signal,
    onopen: () => dispatch('open'),
    onmessage: (message) => dispatch(message.event ?? 'message', message.data),
    onerror: () => {
      dispatch('error')
    },
  })

  return {
    addEventListener(type: string, listener: (event: MessageEvent) => void) {
      if (!listeners.has(type)) {
        listeners.set(type, new Set())
      }
      listeners.get(type)!.add(listener)
    },
    removeEventListener(type: string, listener: (event: MessageEvent) => void) {
      listeners.get(type)?.delete(listener)
    },
    close() {
      controller.abort()
    },
  } as EventSource
}

const transmit = new Transmit({
  baseUrl: 'http://localhost:3333',
  eventSourceFactory: (url, options) => {
    return createFetchEventSource(url, options, {
      Authorization: `Bearer ${token}`,
    })
  },
})

Note: this adapter is minimal and only wires open, error, and message (or custom event names). If you rely on other EventSource features like readyState or onopen, you may want to expand it.

Custom UID Generator

By default, Transmit uses crypto.randomUUID() to generate unique client identifiers. This method only works in secure contexts (HTTPS). If you need to use Transmit over HTTP (e.g., local network deployments), you can provide a custom uidGenerator function.

const transmit = new Transmit({
  baseUrl: 'http://localhost:3333',
  uidGenerator: () => {
    return Array.from({ length: 16 }, () =>
      Math.floor(Math.random() * 256).toString(16).padStart(2, '0')
    ).join('')
  },
})

Or using a library like uuid:

import { v4 as uuid } from 'uuid'

const transmit = new Transmit({
  baseUrl: 'http://localhost:3333',
  uidGenerator: () => uuid(),
})

Reconnecting

The transmit client will automatically reconnect to the server when the connection is lost. You can change the number of retries and hook into the reconnect lifecycle as follows:

const transmit = new Transmit({
  baseUrl: 'http://localhost:3333',
  maxReconnectionAttempts: 5,
  onReconnectAttempt: (attempt) => {
    console.log('Reconnect attempt ' + attempt)
  },
  onReconnectFailed: () => {
    console.log('Reconnect failed')
  },
})

Events

The Transmit class uses the EventTarget class to emits multiple events.

transmit.on('connected', () => {
  console.log('connected')
})

transmit.on('disconnected', () => {
  console.log('disconnected')
})

transmit.on('reconnecting', () => {
  console.log('reconnecting')
})

That means you can also remove an event listener previously registered, by passing the event listener function itself.

const onConnected = () => {
  console.log('connected')
}

transmit.on('connected', onConnected)
transmit.off('connected', onConnected)

版本与发布记录

@adonisjs/transmit-client 共发布 17 个版本,首次发布于 2023/07/08;过去 12 个月发布了 1 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.1.0latest2026/01/189 个月前
1.0.02024/04/242 年前
0.2.22024/04/212 年前
0.2.12024/04/102 年前
0.2.02024/04/102 年前
0.1.62024/03/092 年前

关于 @adonisjs/transmit-client 的常见问题

@adonisjs/transmit-client 是什么?

A client for the native Server-Sent-Event module of AdonisJS.

如何安装 @adonisjs/transmit-client?

在项目目录运行 npm install @adonisjs/transmit-client,或使用 pnpm add / yarn add / bun add。

@adonisjs/transmit-client 支持 TypeScript 吗?

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

@adonisjs/transmit-client 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@adonisjs/transmit-client 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18.16.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@adonisjs/transmit-client 可以商用吗?

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

@adonisjs/transmit-client 的下载量有多少?

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

@adonisjs/transmit-client 还在维护吗?

最新版本 1.1.0 发布于 2026/01/18(9 个月前);至今共发布 17 个版本,其中过去 12 个月发布了 1 个;首次发布于 2023/07/08。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。