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
Raw Normal View History

/**
* User Web Sockets requests handler implementation
*
* @author Pierre Hubert
*/
import { BaseRequestsHandler } from "./BaseRequestsHandler";
2020-03-31 16:20:35 +02:00
import { ActiveClient, UserWebSocketController } from "../controllers/UserWebSocketController";
2020-03-31 14:53:46 +02:00
import { WsMessage } from "./WsMessage";
export class UserWebSocketRequestsHandler extends BaseRequestsHandler {
2020-03-31 16:20:35 +02:00
private sentResponse = false;
2020-04-01 10:44:49 +02:00
constructor(public wsClient: ActiveClient, private req: WsMessage) {
super();
}
2020-03-31 16:32:25 +02:00
public get isResponseSent() : boolean {
return this.sentResponse;
}
protected get userID(): number {
return this.wsClient.userID;
}
2020-03-31 14:53:46 +02:00
protected getPostParam(name: string) {
2020-03-31 16:37:52 +02:00
return this.req.data[name];
}
2020-03-31 16:20:35 +02:00
public hasPostParameter(name: string): boolean {
2020-03-31 16:37:52 +02:00
return this.req.data.hasOwnProperty(name)
&& this.req.data[name] != null
&& this.req.data[name] != undefined;
}
2020-03-31 16:20:35 +02:00
public error(code: number, message: string): void {
2020-03-31 16:28:35 +02:00
this.sendResponse("error", {
code: code,
message: message
});
2020-03-31 16:34:32 +02:00
throw new Error("User WS error ("+code+"): "+message);
}
2020-03-31 16:20:35 +02:00
public success(message: string = ""): void {
2020-03-31 16:20:35 +02:00
this.sendResponse("success", message);
}
2020-03-31 16:20:35 +02:00
public send(data: any): void {
2020-03-31 16:20:35 +02:00
this.sendResponse("success", data);
}
2020-03-31 16:20:35 +02:00
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
2020-04-01 17:55:44 +02:00
UserWebSocketController.SendToClient(this.wsClient, new WsMessage({
2020-03-31 16:20:35 +02:00
title: title,
data: data,
id: this.req.id
}))
this.sentResponse = true;
}
}