Refactor register page

This commit is contained in:
thierryverse 2025-11-15 02:07:20 +02:00
parent 82fea0ceee
commit 41a938cec0
24 changed files with 292 additions and 196 deletions

View file

@ -1,11 +1,12 @@
import {
type LoginRequest,
loginRequest,
LoginRequest,
loginResponse,
type RegisterRequest,
registerRequest,
RegisterRequest,
registerResponse,
} from "@/contracts/types/auth.types";
import { ValidationError } from "../error";
import { baseApiService } from "./base-api.service";
export class AuthApiService {
@ -14,7 +15,11 @@ export class AuthApiService {
const parsedRequest = loginRequest.safeParse(request);
if (!parsedRequest.success) {
throw new Error(`Invalid request: ${parsedRequest.error.message}`);
console.error("Invalid request:", parsedRequest.error);
// Format a user frendly error message
const errorMessage = parsedRequest.error.errors.map((err) => err.message).join(", ");
throw new ValidationError(`Invalid request: ${errorMessage}`, undefined, "VALLIDATION_ERROR");
}
return baseApiService.post(`/auth/jwt/login`, parsedRequest.data, loginResponse, {
@ -27,9 +32,15 @@ export class AuthApiService {
const parsedRequest = registerRequest.safeParse(request);
if (!parsedRequest.success) {
throw new Error(`Invalid request: ${parsedRequest.error.message}`);
console.error("Invalid request:", parsedRequest.error);
// Format a user frendly error message
const errorMessage = parsedRequest.error.errors.map((err) => err.message).join(", ");
throw new ValidationError(`Invalid request: ${errorMessage}`);
}
return baseApiService.post(`/auth/register`, parsedRequest.data, registerResponse);
};
}
export const authApiService = new AuthApiService();

View file

@ -1,5 +1,11 @@
import z from "zod";
import { AppError, AuthenticationError, AuthorizationError, ValidationError } from "../error";
import type z from "zod";
import {
AppError,
AuthenticationError,
AuthorizationError,
NotFoundError,
ValidationError,
} from "../error";
export type RequestOptions = {
method: "GET" | "POST" | "PUT" | "DELETE";
@ -14,6 +20,8 @@ export class BaseApiService {
bearerToken: string;
baseUrl: string;
noAuthEndpoints: string[] = ["/auth/jwt/login", "/auth/register"];
constructor(bearerToken: string, baseUrl: string) {
this.bearerToken = bearerToken;
this.baseUrl = baseUrl;
@ -29,84 +37,123 @@ export class BaseApiService {
responseSchema?: z.ZodSchema<T>,
options?: RequestOptions
): Promise<T> {
const defaultOptions: RequestOptions = {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.bearerToken}`,
},
method: "GET",
};
try {
const defaultOptions: RequestOptions = {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.bearerToken || ""}`,
},
method: "GET",
};
const mergedOptions: RequestOptions = {
...defaultOptions,
...(options ?? {}),
headers: {
...defaultOptions.headers,
...(options?.headers ?? {}),
},
};
const mergedOptions: RequestOptions = {
...defaultOptions,
...(options ?? {}),
headers: {
...defaultOptions.headers,
...(options?.headers ?? {}),
},
};
let requestBody;
// biome-ignore lint/suspicious: Unknown
let requestBody;
// Serialize body
if (body) {
if (mergedOptions.headers?.["Content-Type"].toLocaleLowerCase() === "application/json") {
requestBody = JSON.stringify(body);
// Serialize body
if (body) {
if (mergedOptions.headers?.["Content-Type"].toLocaleLowerCase() === "application/json") {
requestBody = JSON.stringify(body);
}
if (
mergedOptions.headers?.["Content-Type"].toLocaleLowerCase() ===
"application/x-www-form-urlencoded"
) {
requestBody = new URLSearchParams(body);
}
mergedOptions.body = requestBody;
}
if (
mergedOptions.headers?.["Content-Type"].toLocaleLowerCase() ===
"application/x-www-form-urlencoded"
) {
requestBody = new URLSearchParams(body);
if (!this.baseUrl) {
throw new AppError("Base URL is not set.");
}
mergedOptions.body = requestBody;
}
if (!this.baseUrl) {
throw new AppError("Base URL is not set.");
}
if (!this.bearerToken) {
throw new AuthenticationError("You are not authenticated. Please login again.");
}
const fullUrl = new URL(url, this.baseUrl).toString();
const response = await fetch(fullUrl, mergedOptions);
if (!response.ok) {
if (response.status === 401) {
if (!this.bearerToken && !this.noAuthEndpoints.includes(url)) {
throw new AuthenticationError("You are not authenticated. Please login again.");
}
if (response.status === 403) {
throw new AuthorizationError("You don't have permission to access this resource.");
const fullUrl = new URL(url, this.baseUrl).toString();
const response = await fetch(fullUrl, mergedOptions);
if (!response.ok) {
// biome-ignore lint/suspicious: Unknown
let data;
try {
data = await response.json();
} catch (error) {
console.error("Failed to parse response as JSON:", error);
throw new AppError("Something went wrong", response.status, response.statusText);
}
// for fastapi errors response
if ("detail" in data) {
throw new AppError(data.detail, response.status, response.statusText);
}
switch (response.status) {
case 401:
throw new AuthenticationError(
"You are not authenticated. Please login again.",
response.status,
response.statusText
);
case 403:
throw new AuthorizationError(
"You don't have permission to access this resource.",
response.status,
response.statusText
);
case 404:
throw new NotFoundError("Resource not found", response.status, response.statusText);
// Add more cases as needed
default:
throw new AppError("Something went wrong", response.status, response.statusText);
}
}
throw new AppError(`API Error: ${response.statusText}`);
}
// biome-ignore lint/suspicious: Unknown
let data;
let data;
try {
data = await response.json();
} catch (error) {
console.error("Failed to parse response as JSON:", error);
try {
data = await response.json();
} catch (error) {
throw new AppError(`Failed to parse response as JSON: ${error}`);
}
throw new AppError("Something went wrong", response.status, response.statusText);
}
if (!responseSchema) {
return data;
}
const parsedData = responseSchema.safeParse(data);
if (!parsedData.success) {
/** The request was successful, but the response data does not match the expected schema.
* This is a client side error, and should be fixed by updating the responseSchema to keep things typed.
* This error should not be shown to the user , it is for dev only.
*/
console.error("Invalid API response schema:", parsedData.error);
}
if (!responseSchema) {
return data;
} catch (error) {
console.error("Request failed:", error);
throw error;
}
const parsedData = responseSchema.safeParse(data);
if (!parsedData.success) {
throw new ValidationError(`Invalid response: ${parsedData.error.message}`);
}
return parsedData.data;
}
async get<T>(

View file

@ -1,21 +1,21 @@
import { ResearchMode } from "@/components/chat/types";
import { Message } from "@ai-sdk/react";
import { z } from "zod";
import { ResearchMode } from "@/components/chat/types";
import {
type CreateChatRequest,
chatDetails,
chatSummary,
createChatRequest,
CreateChatRequest,
type DeleteChatRequest,
deleteChatRequest,
DeleteChatRequest,
getChatDetailsRequest,
GetChatDetailsRequest,
getChatsBySearchSpaceRequest,
GetChatsBySearchSpaceRequest,
deleteChatResponse,
UpdateChatRequest,
type GetChatDetailsRequest,
type GetChatsBySearchSpaceRequest,
getChatDetailsRequest,
getChatsBySearchSpaceRequest,
type UpdateChatRequest,
updateChatRequest,
} from "@/contracts/types/chat.types";
import { z } from "zod";
import { baseApiService } from "./base-api.service";
export class ChatApiService {

View file

@ -1,6 +1,6 @@
import type { Message } from "@ai-sdk/react";
import type { Chat, ChatDetails } from "@/app/dashboard/[search_space_id]/chats/chats-client";
import { ResearchMode } from "@/components/chat/types";
import { Message } from "@ai-sdk/react";
import type { ResearchMode } from "@/components/chat/types";
export const fetchChatDetails = async (
chatId: string,

View file

@ -1,5 +1,5 @@
import { DocumentWithChunks } from "@/hooks/use-document-by-chunk";
import { DocumentTypeCount } from "@/hooks/use-document-types";
import type { DocumentWithChunks } from "@/hooks/use-document-by-chunk";
import type { DocumentTypeCount } from "@/hooks/use-document-types";
import { normalizeListResponse } from "../pagination";
export const uploadDocument = async (formData: FormData, authToken: string) => {

View file

@ -1,4 +1,4 @@
import { CreateLLMConfig, LLMConfig, UpdateLLMConfig } from "@/hooks/use-llm-configs";
import type { CreateLLMConfig, LLMConfig, UpdateLLMConfig } from "@/hooks/use-llm-configs";
export const fetchLLMConfigs = async (searchSpaceId: number, authToken: string) => {
const response = await fetch(

View file

@ -1,4 +1,4 @@
import { Connector, CreateConnectorRequest } from "@/hooks/use-connectors";
import type { Connector, CreateConnectorRequest } from "@/hooks/use-connectors";
export const createConnector = async (
data: CreateConnectorRequest,