[mod] 先優化為Class
This commit is contained in:
@@ -58,33 +58,56 @@ export class NetConnector {
|
||||
try {
|
||||
// 动态导入文件
|
||||
const module = await import(`../../../../api/${req.Method.replace(".", "/")}`);
|
||||
const isClass = typeof module.default === 'function' && module.default.prototype && Object.getOwnPropertyNames(module.default.prototype).includes('constructor');
|
||||
|
||||
// 调用导入模块中的处理函数
|
||||
if (module.default) {
|
||||
let AsyncFunction: () => IterableIterator<any> = function* (): IterableIterator<any> {
|
||||
const clientData: ClientData = NetConnector.clients.get(socket);
|
||||
const response: INetResponse<any> = yield* module.default(clientData, req);
|
||||
if (response) {
|
||||
NetConnector.Send(socket, response);
|
||||
}
|
||||
};
|
||||
CoroutineV2.Single(AsyncFunction()).Start();
|
||||
if (isClass) {
|
||||
const moduleClass = new module.default();
|
||||
let AsyncFunction: () => IterableIterator<any> = function* (): IterableIterator<any> {
|
||||
const clientData: ClientData = NetConnector.clients.get(socket);
|
||||
const method: string = req.Method.split(".")[1];
|
||||
try {
|
||||
const response: INetResponse<any> = yield* moduleClass[method](clientData, req);
|
||||
if (response) {
|
||||
NetConnector.Send(socket, response);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error handling request ${req.Method}: ${error.message}`);
|
||||
NetConnector.sendError(socket, req);
|
||||
}
|
||||
};
|
||||
CoroutineV2.Single(AsyncFunction()).Start();
|
||||
} else {
|
||||
let AsyncFunction: () => IterableIterator<any> = function* (): IterableIterator<any> {
|
||||
const clientData: ClientData = NetConnector.clients.get(socket);
|
||||
const response: INetResponse<any> = yield* module.default(clientData, req);
|
||||
if (response) {
|
||||
NetConnector.Send(socket, response);
|
||||
}
|
||||
};
|
||||
CoroutineV2.Single(AsyncFunction()).Start();
|
||||
}
|
||||
} else {
|
||||
throw new Error(`Module for ${req.Method} does not export a default function.`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error handling request ${req.Method}: ${error.message}`);
|
||||
const response: INetResponse<any> = {
|
||||
Status: -1,
|
||||
Method: req.Method,
|
||||
Data: null,
|
||||
IsValid: false
|
||||
};
|
||||
NetConnector.Send(socket, response);
|
||||
NetConnector.sendError(socket, req);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static sendError(socket: WebSocket, req: INetRequest<any>) {
|
||||
const response: INetResponse<any> = {
|
||||
Status: -1,
|
||||
Method: req.Method,
|
||||
Data: null,
|
||||
IsValid: false
|
||||
};
|
||||
NetConnector.Send(socket, response);
|
||||
}
|
||||
|
||||
public static OnWebSocketClose() {
|
||||
console.log('Client disconnected');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user