52 lines
1.3 KiB
TypeScript
52 lines
1.3 KiB
TypeScript
import { SSESession } from '../utils/sse-session.js';
|
|
import { BaseTransport } from './base-transport.js';
|
|
|
|
export class TransportSSE extends BaseTransport {
|
|
static async from(url: string) {
|
|
const session = await SSESession.from(url);
|
|
return new TransportSSE(session);
|
|
}
|
|
|
|
static fromSSESession(session: SSESession) {
|
|
return new TransportSSE(session);
|
|
}
|
|
|
|
constructor(private readonly session: SSESession) {
|
|
super();
|
|
|
|
console.log('created transport sse');
|
|
|
|
this.session.on('message', (message) => this.emit('message', message));
|
|
this.session.on('connected', () => this.emit('connected', true));
|
|
this.session.on('disconnected', () => this.emit('disconnected', true));
|
|
}
|
|
|
|
/**
|
|
* Send fetch request to the url, ignoring SSE client as it's not needed for this transport
|
|
* @param url - The URL to send the message to
|
|
* @param body - The body to send
|
|
*/
|
|
async send(url: string, body: unknown): Promise<unknown> {
|
|
const response = await fetch(url, {
|
|
method: 'POST',
|
|
body: JSON.stringify(body),
|
|
});
|
|
|
|
return response.json();
|
|
}
|
|
|
|
/**
|
|
* Connect the SSE session
|
|
*/
|
|
async connect(): Promise<void> {
|
|
await this.session.connect();
|
|
}
|
|
|
|
/**
|
|
* Disconnect the SSE session
|
|
*/
|
|
async disconnect(): Promise<void> {
|
|
this.session.close();
|
|
}
|
|
}
|