Server/project/src/callbacks/ItemEventCallbacks.ts
Alex aee391ec1d Null checks first pass (!353)
Co-authored-by: clodan <clodan@clodan.com>
Reviewed-on: https://dev.sp-tarkov.com/SPT/Server/pulls/353
2024-05-27 16:05:16 +00:00

67 lines
2.3 KiB
TypeScript

import { inject, injectable } from "tsyringe";
import { IGetBodyResponseData } from "@spt/models/eft/httpResponse/IGetBodyResponseData";
import { Warning } from "@spt/models/eft/itemEvent/IItemEventRouterBase";
import { IItemEventRouterRequest } from "@spt/models/eft/itemEvent/IItemEventRouterRequest";
import { IItemEventRouterResponse } from "@spt/models/eft/itemEvent/IItemEventRouterResponse";
import { BackendErrorCodes } from "@spt/models/enums/BackendErrorCodes";
import { ItemEventRouter } from "@spt/routers/ItemEventRouter";
import { HttpResponseUtil } from "@spt/utils/HttpResponseUtil";
@injectable()
export class ItemEventCallbacks
{
constructor(
@inject("HttpResponseUtil") protected httpResponse: HttpResponseUtil,
@inject("ItemEventRouter") protected itemEventRouter: ItemEventRouter,
)
{}
public async handleEvents(
url: string,
info: IItemEventRouterRequest,
sessionID: string,
): Promise<IGetBodyResponseData<IItemEventRouterResponse>>
{
const eventResponse = await this.itemEventRouter.handleEvents(info, sessionID);
const result = this.isCriticalError(eventResponse.warnings)
? this.httpResponse.getBody(
eventResponse,
this.getErrorCode(eventResponse.warnings),
eventResponse.warnings[0].errmsg,
)
: this.httpResponse.getBody(eventResponse);
return result;
}
/**
* Return true if the passed in list of warnings contains critical issues
* @param warnings The list of warnings to check for critical errors
* @returns
*/
private isCriticalError(warnings: Warning[]): boolean
{
// List of non-critical error codes, we return true if any error NOT included is passed in
const nonCriticalErrorCodes: BackendErrorCodes[] = [BackendErrorCodes.NOTENOUGHSPACE];
for (const warning of warnings)
{
if (!nonCriticalErrorCodes.includes(+(warning?.code ?? "0")))
{
return true;
}
}
return false;
}
protected getErrorCode(warnings: Warning[]): number
{
if (warnings[0]?.code)
{
return Number(warnings[0].code);
}
return BackendErrorCodes.UNKNOWN_ERROR;
}
}