MCPcopy Index your code
hub / github.com/scriptscat/scriptcat / subscribe

Method subscribe

packages/message/message_queue.ts:128–157  ·  view source on GitHub ↗
(topic: string, handler: MessageHandler<T>)

Source from the content-addressed store, hash-verified

126
127 // 订阅消息
128 subscribe<T>(topic: string, handler: MessageHandler<T>) {
129 const fullTopic = `${this.name}${topic}`;
130
131 if (this.middlewares.length === 0) {
132 // 没有中间件,直接订阅
133 return this.messageQueue.subscribe(fullTopic, handler);
134 } else {
135 // 有中间件,需要包装处理函数
136 const wrappedHandler = async (message: T) => {
137 let index = 0;
138
139 const next = async (): Promise<void> => {
140 if (index < this.middlewares.length) {
141 const middleware = this.middlewares[index++];
142 const result = middleware(fullTopic, message, next);
143 if (result instanceof Promise) {
144 await result;
145 }
146 } else {
147 // 所有中间件都执行完毕,执行最终的处理函数
148 handler(message);
149 }
150 };
151
152 await next();
153 };
154
155 return this.messageQueue.subscribe(fullTopic, wrappedHandler);
156 }
157 }
158
159 // 发布消息
160 publish<T>(topic: string, message: NonNullable<T>) {

Callers

nothing calls this directly

Calls 1

subscribeMethod · 0.65

Tested by

no test coverage detected