MCPcopy Create free account
hub / github.com/scriptscat/scriptcat / Server

Class Server

packages/message/server.ts:129–232  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

127};
128
129export class Server {
130 private apiFunctionMap: Map<string, ApiFunction> = new Map();
131
132 private logger = LoggerCore.getInstance().logger({ service: "messageServer" });
133
134 constructor(
135 prefix: string,
136 msgReceiver: Message | Message[],
137 private enableConnect: boolean = true
138 ) {
139 const msgReceiverList = Array.isArray(msgReceiver) ? msgReceiver : [msgReceiver];
140 if (this.enableConnect) {
141 msgReceiverList.forEach((msg) => {
142 msg.onConnect((msg: TMessage, con: MessageConnect) => {
143 if (typeof msg.action !== "string") return;
144 this.logger.trace("server onConnect", { msg });
145 if (msg.action?.startsWith(prefix)) {
146 return this.connectHandle(msg.action.slice(prefix.length + 1), msg.data, con);
147 }
148 return false;
149 });
150 });
151 }
152
153 msgReceiverList.forEach((msg) => {
154 msg.onMessage((msg: TMessage, sendResponse, sender) => {
155 if (typeof msg.action !== "string") return;
156 this.logger.trace("server onMessage", { msg: msg as any });
157 if (msg.action?.startsWith(prefix)) {
158 return this.messageHandle(msg.action.slice(prefix.length + 1), msg.data, sendResponse, sender);
159 }
160 });
161 return false;
162 });
163 }
164
165 group(name: string, middleware?: MiddlewareFunction) {
166 return new Group(this, name, middleware);
167 }
168
169 on(name: string, func: ApiFunction) {
170 this.apiFunctionMap.set(name, func);
171 }
172
173 private connectHandle(msg: string, params: any, con: MessageConnect) {
174 const func = this.apiFunctionMap.get(msg);
175 if (func) {
176 const ret = func(params, new SenderConnect(con));
177 if (ret) {
178 if (ret instanceof Promise) {
179 ret
180 .then((data) => {
181 data && con.sendMessage({ code: 0, data });
182 })
183 .catch((e: Error) => {
184 con.sendMessage({ code: -1, message: formatErrorToClient(e) });
185 this.logger.error("connectHandle error", Logger.E(e));
186 });

Callers

nothing calls this directly

Calls 2

getInstanceMethod · 0.80
loggerMethod · 0.45

Tested by

no test coverage detected