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

Class Group

packages/message/server.ts:234–288  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

232}
233
234export class Group {
235 private middlewares: MiddlewareFunction[] = [];
236
237 constructor(
238 private server: Server,
239 private name: string,
240 middleware?: MiddlewareFunction
241 ) {
242 if (!name.endsWith("/") && name.length > 0) {
243 this.name += "/";
244 }
245 if (middleware) {
246 this.middlewares.push(middleware);
247 }
248 }
249
250 group(name: string, middleware?: MiddlewareFunction) {
251 const newGroup = new Group(this.server, `${this.name}${name}`, middleware);
252 // 继承父级的中间件
253 newGroup.middlewares = [...this.middlewares, ...newGroup.middlewares];
254 return newGroup;
255 }
256
257 use(middleware: MiddlewareFunction): Group {
258 const newGroup = new Group(this.server, `${this.name}`, middleware);
259 newGroup.middlewares = [...this.middlewares, ...newGroup.middlewares];
260 return newGroup;
261 }
262
263 on(name: string, func: ApiFunction) {
264 const fullName = `${this.name}${name}`;
265
266 if (this.middlewares.length === 0) {
267 // 没有中间件,直接注册
268 this.server.on(fullName, func);
269 } else {
270 // 有中间件,需要包装处理函数
271 this.server.on(fullName, async (params: any, con: IGetSender) => {
272 let index = 0;
273
274 const next = async (): Promise<any> => {
275 if (index < this.middlewares.length) {
276 const middleware = this.middlewares[index++];
277 return await middleware(params, con, next);
278 } else {
279 // 所有中间件都执行完毕,执行最终的处理函数
280 return await func(params, con);
281 }
282 };
283
284 return await next();
285 });
286 }
287 }
288}
289
290// 转发消息
291export function forwardMessage(

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected