refactor: generalize API library

This commit is contained in:
spiral
2022-02-01 15:24:45 -05:00
parent 6d2fa78767
commit e74b5e1c13
26 changed files with 229 additions and 487 deletions

28
src/api/errors.ts Normal file
View File

@@ -0,0 +1,28 @@
enum ErrorType {
Unknown = 0,
InvalidToken = 401,
NotFound = 404,
InternalServerError = 500,
}
interface ApiError {
code: number,
type: ErrorType,
message?: string,
data?: any,
}
export function parse(code: number, data?: string): ApiError {
var type = ErrorType[ErrorType[code]] ?? ErrorType.Unknown;
if (code >= 500) type = ErrorType.InternalServerError;
var err: ApiError = { code, type };
if (data) {
var d = JSON.parse(data);
err.message = d.message;
err.data = d;
}
return err;
}