significant refactor

This commit is contained in:
2025-08-30 01:42:23 -05:00
parent 7136f646a3
commit 052f53444e
106 changed files with 1994 additions and 1701 deletions

View File

@@ -0,0 +1,103 @@
import { logger } from "../../logger";
import { ErrorType, ServerError, ServerResult } from "../types";
export const createServerError = (
type: ErrorType,
message: string,
userMessage: string,
statusCode?: number,
context?: Record<string, any>
): ServerError => ({
code: type,
message,
userMessage,
statusCode,
context,
});
export const toServerResult = async <T>(serverFn: () => Promise<T>): Promise<ServerResult<T>> => {
try {
const data = await serverFn();
return { success: true, data };
} catch (error) {
logger.error('Server Fn Error', error);
const mappedError = mapKnownError(error);
return { success: false, error: mappedError };
}
};
const mapKnownError = (error: unknown): ServerError => {
if (error && typeof error === "object" && "status" in error) {
const pbError = error as {
status: number;
message: string;
data?: unknown;
};
switch (pbError.status) {
case 400:
return createServerError(
ErrorType.VALIDATION,
pbError.message,
"Invalid request",
400,
{ originalError: pbError.data }
);
case 401:
return createServerError(
ErrorType.UNAUTHORIZED,
pbError.message,
"You are not authorized to perform this action",
401
);
case 403:
return createServerError(
ErrorType.FORBIDDEN,
pbError.message,
"Access denied",
403
);
case 404:
return createServerError(
ErrorType.NOT_FOUND,
pbError.message,
"The requested resource was not found",
404
);
default:
return createServerError(
ErrorType.POCKETBASE,
pbError.message,
"Something went wrong. Please try again.",
pbError.status
);
}
}
if (error instanceof TypeError && error.message.includes("fetch")) {
return createServerError(
ErrorType.NETWORK,
error.message,
"Network error. Please check your connection and try again."
);
}
if (error instanceof Error) {
return createServerError(
ErrorType.UNKNOWN,
error.message,
"An unexpected error occurred. Please try again.",
undefined,
{ stack: error.stack }
);
}
return createServerError(
ErrorType.UNKNOWN,
String(error),
"An unexpected error occurred. Please try again.",
undefined,
{ originalError: error }
);
};