import {WebsocketAppServer} from "../WebsocketAppServer"; import {IConnection} from "../Transport/Connection/IConnection"; export abstract class ServerResponseAbstract { public statusCode: number = 200; public payload: any; public payloadClass: string|null; public event: string; status(statusCode: number) { this.statusCode = statusCode; } get(key) { if(this.hasOwnProperty(key)) { return this[key]; } return undefined; } has(key) { return this.hasOwnProperty(key); } } export interface ServerResponseInterface { statusCode?: number; payload?: any; payloadClass?: string|null; event?: string; } export class ServerResponse { public server: WebsocketAppServer; public requestId: string|null; public statusCode: number = 200; public payload: any; public payloadClass: string|null; public event: string; constructor( public connection: IConnection ) { this.server = this.connection.server; } loadAbstract(abstract: ServerResponseAbstract) { if(abstract.has("statusCode")) this.statusCode = abstract.get("statusCode"); if(abstract.has("payload")) this.payload = abstract.get("payload"); if(abstract.has("payloadClass")) this.payloadClass = abstract.get("payloadClass"); if(abstract.has("event")) this.event = abstract.get("event"); return this; } loadAttributes(responseAttributes: ServerResponseInterface) { this.set(responseAttributes, [ "payload", "payloadClass", "event", "statusCode" ]); } private set(attributes: ServerResponseInterface, props: Array) { for(let prop of props) { if(attributes.hasOwnProperty(prop)) { this[prop] = attributes[prop]; } } } toObject() { return { requestId: this.requestId, statusCode: this.statusCode, payload: this.payload, payloadClass: this.payloadClass, event: this.event } } toJSON() { return JSON.stringify(this.toObject()); } send() { try { console.log("Responding to client: "); console.log(this.toObject()); this.connection.sendResponse(this); } catch (error) { console.error(error); } return this; } to(requestId: string) { this.requestId = requestId; return this; } status(statusCode: number) { this.statusCode = statusCode; return this; } with(payload: any) { this.payload = payload; return this; } asClass(payloadClass: string) { this.payloadClass = payloadClass; return this; } triggering(event: string) { this.event = event; return this; } }