extends the base apis to support blob response

This commit is contained in:
thierryverse 2025-11-18 10:43:45 +02:00
parent 8015eb8e94
commit b2da1aa8e9

View file

@ -1,187 +1,231 @@
import type z from "zod"; import type z from "zod";
import { import {
AppError, AppError,
AuthenticationError, AuthenticationError,
AuthorizationError, AuthorizationError,
NotFoundError, NotFoundError,
ValidationError,
} from "../error"; } from "../error";
export type RequestOptions = { export type RequestOptions = {
method: "GET" | "POST" | "PUT" | "DELETE"; method: "GET" | "POST" | "PUT" | "DELETE";
headers?: Record<string, string>; headers?: Record<string, string>;
contentType?: "application/json" | "application/x-www-form-urlencoded"; contentType?: "application/json" | "application/x-www-form-urlencoded";
signal?: AbortSignal; signal?: AbortSignal;
body?: any; body?: any;
// Add more options as needed responseType?: "json" | "text" | "blob" | "arrayBuffer"; // Add more response types as needed
// Add more options as needed
}; };
export class BaseApiService { class BaseApiService {
bearerToken: string; bearerToken: string;
baseUrl: string; baseUrl: string;
noAuthEndpoints: string[] = ["/auth/jwt/login", "/auth/register", "/auth/refresh"]; // Add more endpoints as needed noAuthEndpoints: string[] = [
"/auth/jwt/login",
"/auth/register",
"/auth/refresh",
]; // Add more endpoints as needed
constructor(bearerToken: string, baseUrl: string) { constructor(bearerToken: string, baseUrl: string) {
this.bearerToken = bearerToken; this.bearerToken = bearerToken;
this.baseUrl = baseUrl; this.baseUrl = baseUrl;
} }
setBearerToken(bearerToken: string) { setBearerToken(bearerToken: string) {
this.bearerToken = bearerToken; this.bearerToken = bearerToken;
} }
async request<T>( async request<T>(
url: string, url: string,
responseSchema?: z.ZodSchema<T>, responseSchema?: z.ZodSchema<T>,
options?: RequestOptions options?: RequestOptions
): Promise<T> { ): Promise<T> {
try { try {
const defaultOptions: RequestOptions = { const defaultOptions: RequestOptions = {
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
Authorization: `Bearer ${this.bearerToken || ""}`, Authorization: `Bearer ${this.bearerToken || ""}`,
}, },
method: "GET", method: "GET",
}; responseType: "json",
};
const mergedOptions: RequestOptions = { const mergedOptions: RequestOptions = {
...defaultOptions, ...defaultOptions,
...(options ?? {}), ...(options ?? {}),
headers: { headers: {
...defaultOptions.headers, ...defaultOptions.headers,
...(options?.headers ?? {}), ...(options?.headers ?? {}),
}, },
}; };
if (!this.baseUrl) { if (!this.baseUrl) {
throw new AppError("Base URL is not set."); throw new AppError("Base URL is not set.");
} }
if (!this.bearerToken && !this.noAuthEndpoints.includes(url)) { if (!this.bearerToken && !this.noAuthEndpoints.includes(url)) {
throw new AuthenticationError("You are not authenticated. Please login again."); throw new AuthenticationError(
} "You are not authenticated. Please login again."
);
}
const fullUrl = new URL(url, this.baseUrl).toString(); const fullUrl = new URL(url, this.baseUrl).toString();
const response = await fetch(fullUrl, mergedOptions); const response = await fetch(fullUrl, mergedOptions);
if (!response.ok) { if (!response.ok) {
// biome-ignore lint/suspicious: Unknown // biome-ignore lint/suspicious: Unknown
let data; let data;
try { try {
data = await response.json(); data = await response.json();
} catch (error) { } catch (error) {
console.error("Failed to parse response as JSON:", error); console.error("Failed to parse response as JSON:", error);
throw new AppError("Something went wrong", response.status, response.statusText); throw new AppError(
} "Something went wrong",
response.status,
response.statusText
);
}
// for fastapi errors response // for fastapi errors response
if ("detail" in data) { if (typeof data === "object" && "detail" in data) {
throw new AppError(data.detail, response.status, response.statusText); throw new AppError(data.detail, response.status, response.statusText);
} }
switch (response.status) { switch (response.status) {
case 401: case 401:
throw new AuthenticationError( throw new AuthenticationError(
"You are not authenticated. Please login again.", "You are not authenticated. Please login again.",
response.status, response.status,
response.statusText response.statusText
); );
case 403: case 403:
throw new AuthorizationError( throw new AuthorizationError(
"You don't have permission to access this resource.", "You don't have permission to access this resource.",
response.status, response.status,
response.statusText response.statusText
); );
case 404: case 404:
throw new NotFoundError("Resource not found", response.status, response.statusText); throw new NotFoundError(
// Add more cases as needed "Resource not found",
default: response.status,
throw new AppError("Something went wrong", response.status, response.statusText); response.statusText
} );
} // Add more cases as needed
default:
throw new AppError(
"Something went wrong",
response.status,
response.statusText
);
}
}
// biome-ignore lint/suspicious: Unknown // biome-ignore lint/suspicious: Unknown
let data; let data;
const responseType = mergedOptions.responseType || "json";
try { try {
data = await response.json(); switch (responseType) {
} catch (error) { case "json":
console.error("Failed to parse response as JSON:", error); data = await response.json();
break;
case "text":
data = await response.text();
break;
case "blob":
data = await response.blob();
break;
case "arrayBuffer":
data = await response.arrayBuffer();
break;
// Add more cases as needed
default:
data = await response.text();
}
} catch (error) {
console.error("Failed to parse response as JSON:", error);
throw new AppError(
"Failed to parse response",
response.status,
response.statusText
);
}
throw new AppError("Something went wrong", response.status, response.statusText); if (responseType === "json") {
} if (!responseSchema) {
return data;
}
const parsedData = responseSchema.safeParse(data);
if (!responseSchema) { if (!parsedData.success) {
return data; /** 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);
}
const parsedData = responseSchema.safeParse(data); return data;
}
if (!parsedData.success) { return data;
/** The request was successful, but the response data does not match the expected schema. } catch (error) {
* This is a client side error, and should be fixed by updating the responseSchema to keep things typed. console.error("Request failed:", error);
* This error should not be shown to the user , it is for dev only. throw error;
*/ }
console.error("Invalid API response schema:", parsedData.error); }
}
return data; async get<T>(
} catch (error) { url: string,
console.error("Request failed:", error); responseSchema?: z.ZodSchema<T>,
throw error; options?: Omit<RequestOptions, "method">
} ) {
} return this.request(url, responseSchema, {
...options,
method: "GET",
});
}
async get<T>( async post<T>(
url: string, url: string,
responseSchema?: z.ZodSchema<T>, responseSchema?: z.ZodSchema<T>,
options?: Omit<RequestOptions, "method"> options?: Omit<RequestOptions, "method">
) { ) {
return this.request(url, responseSchema, { return this.request(url, responseSchema, {
...options, method: "POST",
method: "GET", ...options,
}); });
} }
async post<T>( async put<T>(
url: string, url: string,
responseSchema?: z.ZodSchema<T>, responseSchema?: z.ZodSchema<T>,
options?: Omit<RequestOptions, "method"> options?: Omit<RequestOptions, "method">
) { ) {
return this.request(url, responseSchema, { return this.request(url, responseSchema, {
method: "POST", method: "PUT",
...options, ...options,
}); });
} }
async put<T>( async delete<T>(
url: string, url: string,
responseSchema?: z.ZodSchema<T>, responseSchema?: z.ZodSchema<T>,
options?: Omit<RequestOptions, "method"> options?: Omit<RequestOptions, "method">
) { ) {
return this.request(url, responseSchema, { return this.request(url, responseSchema, {
method: "PUT", method: "DELETE",
...options, ...options,
}); });
} }
async delete<T>(
url: string,
responseSchema?: z.ZodSchema<T>,
options?: Omit<RequestOptions, "method">
) {
return this.request(url, responseSchema, {
method: "DELETE",
...options,
});
}
} }
export const baseApiService = new BaseApiService( export const baseApiService = new BaseApiService(
typeof window !== "undefined" ? localStorage.getItem("surfsense_bearer_token") || "" : "", typeof window !== "undefined"
process.env.NEXT_PUBLIC_FASTAPI_BACKEND_URL || "" ? localStorage.getItem("surfsense_bearer_token") || ""
: "",
process.env.NEXT_PUBLIC_FASTAPI_BACKEND_URL || ""
); );