1
0
mirror of https://gitlab.com/comunic/comunicapiv2 synced 2025-03-13 09:32:38 +00:00
comunicapiv2/src/entities/WebSocketRequestHandler.ts

67 lines
1.5 KiB
TypeScript

/**
* User Web Sockets requests handler implementation
*
* @author Pierre Hubert
*/
import { BaseRequestsHandler } from "./BaseRequestsHandler";
import { ActiveClient, UserWebSocketController } from "../controllers/UserWebSocketController";
import { WsMessage } from "./WsMessage";
export class UserWebSocketRequestsHandler extends BaseRequestsHandler {
private sentResponse = false;
constructor(public wsClient: ActiveClient, private req: WsMessage) {
super();
}
public get isResponseSent() : boolean {
return this.sentResponse;
}
protected get userID(): number {
return this.wsClient.userID;
}
protected getPostParam(name: string) {
return this.req.data[name];
}
public hasPostParameter(name: string): boolean {
return this.req.data.hasOwnProperty(name)
&& this.req.data[name] != null
&& this.req.data[name] != undefined;
}
public error(code: number, message: string): void {
this.sendResponse("error", {
code: code,
message: message
});
throw new Error("User WS error ("+code+"): "+message);
}
public success(message: string = ""): void {
this.sendResponse("success", message);
}
public send(data: any): void {
this.sendResponse("success", data);
}
public sendResponse(title: string, data: any) {
if(this.sentResponse)
throw new Error("Trying to send a response to a request to which a response has already been sent!")
// Send the response
UserWebSocketController.SendToClient(this.wsClient, new WsMessage({
title: title,
data: data,
id: this.req.id
}))
this.sentResponse = true;
}
}