mirror of
https://github.com/skidoodle/budgetable.git
synced 2025-02-15 03:39:14 +01:00
feat: enhance ui components and response handling
This commit is contained in:
parent
78fbcebe91
commit
83b3a747a1
11 changed files with 296 additions and 328 deletions
46
src/lib/helper.ts
Normal file
46
src/lib/helper.ts
Normal file
|
@ -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,
|
||||
});
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue