mirror of
https://github.com/skidoodle/budgetable.git
synced 2026-04-28 15:57:36 +02:00
feat: enhance ui components and response handling
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
type ResponseConstant = {
|
||||
STATUS: number;
|
||||
MESSAGE: string;
|
||||
};
|
||||
|
||||
type ResponseMap = {
|
||||
[key: string]: ResponseConstant;
|
||||
};
|
||||
|
||||
export enum HttpStatus {
|
||||
OK = 200,
|
||||
CREATED = 201,
|
||||
BAD_REQUEST = 400,
|
||||
INTERNAL_SERVER_ERROR = 500,
|
||||
}
|
||||
|
||||
function createResponse(status: number, message: string): ResponseConstant {
|
||||
return { STATUS: status, MESSAGE: message };
|
||||
}
|
||||
|
||||
export const RESPONSE: ResponseMap = {
|
||||
INTERNAL_SERVER_ERROR: createResponse(HttpStatus.INTERNAL_SERVER_ERROR, "Internal server error."),
|
||||
MISSING_ID: createResponse(HttpStatus.BAD_REQUEST, "Missing ID in request."),
|
||||
FAILED_TO_DELETE_DATA: createResponse(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to delete data."),
|
||||
FAILED_TO_UPDATE_DATA: createResponse(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to update data."),
|
||||
INVALID_DATA: createResponse(HttpStatus.BAD_REQUEST, "Invalid data provided."),
|
||||
SUCCESS: createResponse(HttpStatus.OK, "Operation completed successfully."),
|
||||
CREATED: createResponse(HttpStatus.CREATED, "Resource created successfully."),
|
||||
};
|
||||
@@ -0,0 +1,46 @@
|
||||
import { RESPONSE } from "@/lib/const";
|
||||
|
||||
interface ErrorResponse {
|
||||
error: {
|
||||
message: string;
|
||||
details?: unknown;
|
||||
};
|
||||
}
|
||||
|
||||
type SuccessResponse<T> = T;
|
||||
|
||||
type ResponseData<T> = SuccessResponse<T> | ErrorResponse;
|
||||
|
||||
interface ResponseOptions {
|
||||
status?: number;
|
||||
}
|
||||
|
||||
export class ResponseHelper<T = unknown> {
|
||||
private data: ResponseData<T>;
|
||||
private status: number;
|
||||
|
||||
constructor(data: ResponseData<T>, options: ResponseOptions = {}) {
|
||||
this.data = data;
|
||||
this.status = options.status || 200;
|
||||
}
|
||||
|
||||
static success<T>(data: T, status = RESPONSE.SUCCESS.STATUS): Response {
|
||||
return new ResponseHelper<T>(data, { status }).toResponse();
|
||||
}
|
||||
|
||||
static error(
|
||||
constant: (typeof RESPONSE)[keyof typeof RESPONSE],
|
||||
details?: unknown
|
||||
): Response {
|
||||
return new ResponseHelper<ErrorResponse>(
|
||||
{ error: { message: constant.MESSAGE, details } },
|
||||
{ status: constant.STATUS }
|
||||
).toResponse();
|
||||
}
|
||||
|
||||
toResponse(): Response {
|
||||
return Response.json(this.data, {
|
||||
status: this.status,
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user