mirror of
https://github.com/MODSetter/SurfSense.git
synced 2026-04-25 08:46:22 +02:00
Refactor register page
This commit is contained in:
parent
82fea0ceee
commit
41a938cec0
24 changed files with 292 additions and 196 deletions
|
|
@ -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>(
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue