import {AnyErrorCode2StringFormat} from "./AnyErrorCode2StringFormat"; import {AnyErrorCode} from "../../generated/sync/error/AnyErrorCode"; import * as sprintfjs from "sprintf-js"; export type ErrorCodeMap = { [key in AnyErrorCode] : string }; export type ErrorCodeType = ( AnyErrorCode | { index? : number|string, argIndex? : number|string, forcedArg? : any, error : ErrorCodeType } ); export function isIndexErrorCodeType (error : ErrorCodeType) : error is { index : number, error : ErrorCodeType } { return ( typeof error != "string" && typeof (error as any).index == "number" ) } export class ErrorMessageService { public static Map : ErrorCodeMap = AnyErrorCode2StringFormat; public static ToHumanReadable (mixed : any) { if (mixed instanceof RegExp) { return mixed.toString(); } else { return JSON.stringify(mixed); } } public static ToMessageWithMap (map : ErrorCodeMap, name : string, errorCode : ErrorCodeType, mixed : any, args? : any) : string { if (typeof errorCode == "string") { args = ErrorMessageService.ToHumanReadable(args); mixed = ErrorMessageService.ToHumanReadable(mixed); return sprintfjs.sprintf( map[errorCode], name, mixed, args ); } else { if (errorCode.forcedArg != null) { return ErrorMessageService.ToMessageWithMap( map, name, { index : errorCode.index, argIndex : errorCode.argIndex, error : errorCode.error }, mixed, errorCode.forcedArg ); } if (errorCode.argIndex != null) { const nxtArgs = (args != null) ? args[errorCode.argIndex] : undefined; //If we get to this, we fucked up return ErrorMessageService.ToMessageWithMap( map, name, { index : errorCode.index, error : errorCode.error }, mixed, nxtArgs ); } if (errorCode.index != null) { return ErrorMessageService.ToMessageWithMap( map, `${name}[${errorCode.index}]`, errorCode.error, mixed, args ); } return ErrorMessageService.ToMessageWithMap( map, name, errorCode.error, mixed, args ); } } public static ToMessage (name : string, errorCode : ErrorCodeType, mixed : any, args? : any) { return ErrorMessageService.ToMessageWithMap( ErrorMessageService.Map, name, errorCode, mixed, args ); } }