Server/project/src/utils/HttpResponseUtil.ts

73 lines
2.2 KiB
TypeScript
Raw Normal View History

2023-03-03 15:23:46 +00:00
import { inject, injectable } from "tsyringe";
import { IGetBodyResponseData } from "@spt-aki/models/eft/httpResponse/IGetBodyResponseData";
import { INullResponseData } from "@spt-aki/models/eft/httpResponse/INullResponseData";
import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEventRouterResponse";
import { BackendErrorCodes } from "@spt-aki/models/enums/BackendErrorCodes";
import { LocalisationService } from "@spt-aki/services/LocalisationService";
import { JsonUtil } from "@spt-aki/utils/JsonUtil";
2023-03-03 15:23:46 +00:00
@injectable()
export class HttpResponseUtil
{
constructor(
@inject("JsonUtil") protected jsonUtil: JsonUtil,
@inject("LocalisationService") protected localisationService: LocalisationService,
2023-03-03 15:23:46 +00:00
)
{}
2023-03-03 15:23:46 +00:00
protected clearString(s: string): any
{
return s.replace(/[\b]/g, "").replace(/[\f]/g, "").replace(/[\n]/g, "").replace(/[\r]/g, "").replace(
/[\t]/g,
"",
).replace(/[\\]/g, "");
2023-03-03 15:23:46 +00:00
}
/**
* Return passed in data as JSON string
* @param data
* @returns
*/
2023-03-03 15:23:46 +00:00
public noBody(data: any): any
{
return this.clearString(this.jsonUtil.serialize(data));
}
public getBody<T>(data: T, err = 0, errmsg = null): IGetBodyResponseData<T>
{
return this.clearString(this.getUnclearedBody(data, err, errmsg));
}
public getUnclearedBody(data: any, err = 0, errmsg = null): string
{
return this.jsonUtil.serialize({ err: err, errmsg: errmsg, data: data });
2023-03-03 15:23:46 +00:00
}
public emptyResponse(): IGetBodyResponseData<string>
{
return this.getBody("", 0, "");
}
public nullResponse(): INullResponseData
{
return this.clearString(this.getUnclearedBody(null, 0, null));
}
public emptyArrayResponse(): IGetBodyResponseData<any[]>
{
return this.getBody([]);
}
public appendErrorToOutput(
output: IItemEventRouterResponse,
message = this.localisationService.getText("http-unknown_error"),
errorCode = BackendErrorCodes.NONE,
): IItemEventRouterResponse
2023-03-03 15:23:46 +00:00
{
output.warnings = [{ index: 0, errmsg: message, code: errorCode.toString() }];
2023-03-03 15:23:46 +00:00
return output;
}
}