sse

拦截服务器发送事件。

sse 函数是 http 命名空间的一个子集,它可以帮助你创建请求处理程序来拦截服务器发送的事件。

¥The sse function is a subset of the http namespace that helps you create request handlers to intercept Server-Sent Events.

调用签名

¥Call signature

sse<EventMap, Params>(predicate: Path, resolver: ServerSentEventResolver<EventMap, Params>)

sse.ts

Source code for the `sse` function.

解析器参数

¥Resolver argument

除了 http 命名空间公开的所有参数之外,sse 处理程序还具有以下响应解析器属性:

¥In addition to all the arguments exposed by the http namespace, the sse handler has the following response resolver properties:

名称类型描述
clientServerSentEventClient拦截到的 EventSource 实例的表示。
serverServerSentEventServer实际服务器连接对象。

ServerSentEventClient

ServerSentEventClient 对象表示拦截到的 EventSource 实例。你可以使用此对象向客户端发送模拟消息,并关闭或使底层连接出错。

¥The ServerSentEventClient object represents the intercepted EventSource instance. You use this object to send mock messages to the client, close or error the underlying connection.

.send(payload)

  • payload

    • idstring(可选):自定义事件 ID。

      ¥id, string (Optional), a custom event ID.

    • datastring:此事件的已发送数据。

      ¥data, string, the sent data of this event.

    • eventstring(可选):自定义事件类型。

      ¥event, string (Optional), a custom event type.

    • retrynumber(可选):自定义重连时间。如果提供了此选项,则 payload 参数不得设置任何其他属性。

      ¥retry, number (Optional), a custom reconnection time. If this option is provided, no other properties must be set on the payload argument.

向客户端发送模拟事件。

¥Sends a mocked event to the client.

// Send a default "message" event.
client.send({ data: 'hello world' })
 
// Send a custom "greeting" event.
client.send({
	event: 'greeting'
  data: 'Hello, John!',
})
 
// Send an event with a custom ID.
client.send({
	id: 'abc-123',
	event: 'greeting'
  data: 'Hello, John!',
})

.error()

底层 HTTP 连接出错。

¥Errors the underlying HTTP connection.

client.error()

.close()

优雅地关闭底层 HTTP 连接。

¥Gracefully closes the underlying HTTP connection.

client.close()

ServerSentEventServer

ServerSentEventClient 对象表示与实际服务器的连接。使用它来建立连接并监听从服务器接收的事件。

¥The ServerSentEventClient object represents a connection to the actual server. Use it to establish that connection and listen to the received events from the server.

.connect()

…TODO

const source = server.connect()

…待办事项:source 返回的内容以及它的用途(监听消息、关闭连接)。

¥…TODO What is returned as source and what you can use it for (listen to messages, close the connection).

相关材料

¥Related materials

Describing REST API

Learn about describing RESTful APIs.