| 95 | |
| 96 | // 消息队列分组 |
| 97 | export class MessageQueueGroup implements IMessageQueue { |
| 98 | private middlewares: MiddlewareFunction[] = []; |
| 99 | |
| 100 | constructor( |
| 101 | private messageQueue: IMessageQueue, |
| 102 | private name: string, |
| 103 | middleware?: MiddlewareFunction |
| 104 | ) { |
| 105 | if (!name.endsWith("/") && name.length > 0) { |
| 106 | this.name += "/"; |
| 107 | } |
| 108 | if (middleware) { |
| 109 | this.middlewares.push(middleware); |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | // 创建子分组 |
| 114 | group(name: string, middleware?: MiddlewareFunction) { |
| 115 | const newGroup = new MessageQueueGroup(this.messageQueue, `${this.name}${name}`, middleware); |
| 116 | // 继承父级的中间件 |
| 117 | newGroup.middlewares = [...this.middlewares, ...newGroup.middlewares]; |
| 118 | return newGroup; |
| 119 | } |
| 120 | |
| 121 | // 添加中间件 |
| 122 | use(middleware: MiddlewareFunction) { |
| 123 | this.middlewares.push(middleware); |
| 124 | return this; |
| 125 | } |
| 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 |
nothing calls this directly
no outgoing calls
no test coverage detected