update api services

This commit is contained in:
thierryverse 2025-11-18 11:33:57 +02:00
parent e3af39bdbd
commit 7223a7b04d
4 changed files with 51 additions and 92 deletions

View file

@ -9,7 +9,7 @@ import {
import { ValidationError } from "../error"; import { ValidationError } from "../error";
import { baseApiService } from "./base-api.service"; import { baseApiService } from "./base-api.service";
export class AuthApiService { class AuthApiService {
login = async (request: LoginRequest) => { login = async (request: LoginRequest) => {
// Validate the request // Validate the request
const parsedRequest = loginRequest.safeParse(request); const parsedRequest = loginRequest.safeParse(request);

View file

@ -6,13 +6,21 @@ import {
NotFoundError, NotFoundError,
} from "../error"; } from "../error";
enum ResponseType {
JSON = "json",
TEXT = "text",
BLOB = "blob",
ARRAY_BUFFER = "arrayBuffer",
// Add more response types as needed
}
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;
responseType?: "json" | "text" | "blob" | "arrayBuffer"; // Add more response types as needed responseType?: ResponseType;
// Add more options as needed // Add more options as needed
}; };
@ -35,11 +43,21 @@ class BaseApiService {
this.bearerToken = bearerToken; this.bearerToken = bearerToken;
} }
async request<T>( async request<T, R extends ResponseType = ResponseType.JSON>(
url: string, url: string,
responseSchema?: z.ZodSchema<T>, responseSchema?: z.ZodSchema<T>,
options?: RequestOptions options?: RequestOptions & { responseType?: R }
): Promise<T> { ): Promise<
R extends ResponseType.JSON
? T
: R extends ResponseType.TEXT
? string
: R extends ResponseType.BLOB
? Blob
: R extends ResponseType.ARRAY_BUFFER
? ArrayBuffer
: unknown
> {
try { try {
const defaultOptions: RequestOptions = { const defaultOptions: RequestOptions = {
headers: { headers: {
@ -47,7 +65,7 @@ class BaseApiService {
Authorization: `Bearer ${this.bearerToken || ""}`, Authorization: `Bearer ${this.bearerToken || ""}`,
}, },
method: "GET", method: "GET",
responseType: "json", responseType: ResponseType.JSON,
}; };
const mergedOptions: RequestOptions = { const mergedOptions: RequestOptions = {
@ -125,20 +143,20 @@ class BaseApiService {
// biome-ignore lint/suspicious: Unknown // biome-ignore lint/suspicious: Unknown
let data; let data;
const responseType = mergedOptions.responseType || "json"; const responseType = mergedOptions.responseType
try { try {
switch (responseType) { switch (responseType) {
case "json": case ResponseType.JSON:
data = await response.json(); data = await response.json();
break; break;
case "text": case ResponseType.TEXT:
data = await response.text(); data = await response.text();
break; break;
case "blob": case ResponseType.BLOB:
data = await response.blob(); data = await response.blob();
break; break;
case "arrayBuffer": case ResponseType.ARRAY_BUFFER:
data = await response.arrayBuffer(); data = await response.arrayBuffer();
break; break;
// Add more cases as needed // Add more cases as needed
@ -154,7 +172,7 @@ class BaseApiService {
); );
} }
if (responseType === "json") { if (responseType === ResponseType.JSON) {
if (!responseSchema) { if (!responseSchema) {
return data; return data;
} }
@ -181,44 +199,59 @@ class BaseApiService {
async get<T>( async get<T>(
url: string, url: string,
responseSchema?: z.ZodSchema<T>, responseSchema?: z.ZodSchema<T>,
options?: Omit<RequestOptions, "method"> options?: Omit<RequestOptions, "method" | "responseType">
) { ) {
return this.request(url, responseSchema, { return this.request(url, responseSchema, {
...options, ...options,
method: "GET", method: "GET",
responseType: ResponseType.JSON,
}); });
} }
async post<T>( async post<T>(
url: string, url: string,
responseSchema?: z.ZodSchema<T>, responseSchema?: z.ZodSchema<T>,
options?: Omit<RequestOptions, "method"> options?: Omit<RequestOptions, "method" | "responseType">
) { ) {
return this.request(url, responseSchema, { return this.request(url, responseSchema, {
method: "POST", method: "POST",
...options, ...options,
responseType: ResponseType.JSON,
}); });
} }
async put<T>( async put<T>(
url: string, url: string,
responseSchema?: z.ZodSchema<T>, responseSchema?: z.ZodSchema<T>,
options?: Omit<RequestOptions, "method"> options?: Omit<RequestOptions, "method" | "responseType">
) { ) {
return this.request(url, responseSchema, { return this.request(url, responseSchema, {
method: "PUT", method: "PUT",
...options, ...options,
responseType: ResponseType.JSON,
}); });
} }
async delete<T>( async delete<T>(
url: string, url: string,
responseSchema?: z.ZodSchema<T>, responseSchema?: z.ZodSchema<T>,
options?: Omit<RequestOptions, "method"> options?: Omit<RequestOptions, "method" | "responseType">,
) { ) {
return this.request(url, responseSchema, { return this.request(url, responseSchema, {
method: "DELETE", method: "DELETE",
...options, ...options,
responseType: ResponseType.JSON,
});
}
async getBlob(
url: string,
options?: Omit<RequestOptions, "method" | "responseType">
) {
return this.request(url, undefined, {
...options,
method: "GET",
responseType: ResponseType.BLOB,
}); });
} }
} }

View file

@ -17,7 +17,7 @@ import {
import { ValidationError } from "../error"; import { ValidationError } from "../error";
import { baseApiService } from "./base-api.service"; import { baseApiService } from "./base-api.service";
export class ChatApiService { class ChatApiService {
getChatDetails = async (request: GetChatDetailsRequest) => { getChatDetails = async (request: GetChatDetailsRequest) => {
// Validate the request // Validate the request
const parsedRequest = getChatDetailsRequest.safeParse(request); const parsedRequest = getChatDetailsRequest.safeParse(request);
@ -127,4 +127,4 @@ export class ChatApiService {
}; };
} }
export const chatApiService = new ChatApiService(); export const chatsApiService = new ChatApiService();

View file

@ -1,74 +0,0 @@
import type { PodcastItem } from "@/app/dashboard/[search_space_id]/podcasts/podcasts-client";
import type { GeneratePodcastRequest } from "@/components/chat/ChatPanel/ChatPanelContainer";
export const getPodcastByChatId = async (chatId: string, authToken: string) => {
const response = await fetch(
`${process.env.NEXT_PUBLIC_FASTAPI_BACKEND_URL}/api/v1/podcasts/by-chat/${Number(chatId)}`,
{
headers: {
Authorization: `Bearer ${authToken}`,
},
method: "GET",
}
);
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.detail || "Failed to fetch podcast");
}
return (await response.json()) as PodcastItem | null;
};
export const generatePodcast = async (request: GeneratePodcastRequest, authToken: string) => {
const response = await fetch(
`${process.env.NEXT_PUBLIC_FASTAPI_BACKEND_URL}/api/v1/podcasts/generate/`,
{
method: "POST",
headers: {
Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify(request),
}
);
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.detail || "Failed to generate podcast");
}
return await response.json();
};
export const loadPodcast = async (podcast: PodcastItem, authToken: string) => {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 30000);
try {
const response = await fetch(
`${process.env.NEXT_PUBLIC_FASTAPI_BACKEND_URL}/api/v1/podcasts/${podcast.id}/stream`,
{
headers: {
Authorization: `Bearer ${authToken}`,
},
signal: controller.signal,
}
);
if (!response.ok) {
throw new Error(`Failed to fetch audio stream: ${response.statusText}`);
}
const blob = await response.blob();
const objectUrl = URL.createObjectURL(blob);
return objectUrl;
} catch (error) {
if (error instanceof DOMException && error.name === "AbortError") {
throw new Error("Request timed out. Please try again.");
}
throw error;
} finally {
clearTimeout(timeoutId);
}
};