@ fakehost/ 交换
概览
用于构建通过websockets通信的假消息服务的基本包. 可以作为节点服务运行,也可以被捆绑在浏览器内部.
这个图书馆不会给你太多 自己. 相反,它被用来支持运行 相同的假服务代码托管 浏览器内部 或者说 作为节点进程运行。 。 。 .
提供两个主要对象:
WsHost。用于启动网络安全套服务。 它作为一个节点进程运行,它可以从命令行开始,或者从节点测试,例如:快活、活生生、剧作家、网络司机等开始.BrowserWsHost. 用于启动"被嘲笑"的websocket服务. 这直接运行在浏览器内部,对于将"假"服务捆绑在"故事本"内部,或演示应用程序,以及运行Cypress等基于浏览器的测试都是有益的.
不要在生产环境中使用这个。 这是用来测试的 只能做演示.
示例使用
完整的例子见 @ fakehost/ 假信号。 。 。 .
协议处理器
信使服务有多种不同类型的协议来管理信息交换. 其中许多是习俗.
假设我们正在构建一个假协议处理器,用于一个具有以下消息和发出消息结构的服务:
type IncomingMessage = {
destination: string
payload: unknown
}
type OutgoingMessage = {
destination: string
payload: unknown
}
消息全部在JSON中,因此我们可以通过检查网络分页和查看消息来方便地检查服务在做什么.
一个仅支持简单请求/答复消息的极基本协议可能看起来像:
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)
}
}
并让电线 处理器,开始 MyProtocolHandler 作为本地主机服务运行 :
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=@fakehost/exchange
许可证
@ fakehost/ 交换机根据 MIT 许可证。 。 。 .
从 v.x 移动
见 从 v.x 移动