UNPKG

lin-cms-test

Version:

The core library of Lin CMS, this package is just for test!

91 lines (90 loc) 2.42 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const stream_1 = require("stream"); class SSE extends stream_1.Transform { constructor(opts) { super(opts); } _transform(chunk, encoding, cb) { this.push(chunk.toString("utf8")); // this.push("data: " + chunk.toString("utf8") + "\n\n"); cb(); } } exports.SSE = SSE; class MessageBroker { constructor(defaultRetry = 2000) { this.messages = []; this.buffer = []; this.defaultId = 1; this.setRetry(defaultRetry); } setRetry(num) { this.retry = num; this.buffer.push(`retry: ${this.retry}\n`); } setEventId(eventId) { if (eventId) { this.defaultId = eventId; this.buffer.push(`id: ${eventId}\n`); } else { this.buffer.push(`id: ${this.defaultId}\n`); } } resetEventId() { this.setEventId(1); } increaseId() { this.defaultId += 1; } addMessage(event, obj, flush = true) { this.setEventId(); this.buffer.push(`event: ${event}\n`); const line = JSON.stringify(obj); this.buffer.push(`data: ${line}\n\n`); flush && this.flushBuffer(); } flushBuffer() { this.messages.push(this.joinBuffer()); this.buffer.length = 0; this.increaseId(); } joinBuffer() { return this.buffer.join(""); } pop() { // return this.messages.pop(); // 先进先出 const tmp = this.messages[0]; this.messages.splice(0, 1); return tmp; } heartbeat(comment) { // 发送注释 : this is a test stream\n\n 告诉客户端,服务器还活着 if (comment) { this.buffer.push(comment); } else { this.buffer.push(": sse sever is still alive \n\n"); const tmp = this.joinBuffer(); this.buffer.length = 0; return tmp; } } exitMessage() { return this.messages.length > 0; } } exports.MessageBroker = MessageBroker; class Subscription extends stream_1.Readable { constructor(opts) { super(opts); this.value = 0; } _read() { // tslint:disable-next-line: no-empty while (this.push(String(this.value++))) { } } } exports.Subscription = Subscription;