2025-09-25 17:42:36 +09:00
|
|
|
import type { ApiResponse } from "../response-helpers";
|
2025-10-02 17:19:39 +09:00
|
|
|
|
2025-09-19 12:57:39 +09:00
|
|
|
export class ApiError extends Error {
|
|
|
|
|
constructor(
|
|
|
|
|
message: string,
|
|
|
|
|
public readonly response: Response,
|
|
|
|
|
public readonly body?: unknown
|
|
|
|
|
) {
|
|
|
|
|
super(message);
|
|
|
|
|
this.name = "ApiError";
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-09-24 18:00:49 +09:00
|
|
|
export const isApiError = (error: unknown): error is ApiError => error instanceof ApiError;
|
|
|
|
|
|
2025-10-22 10:58:16 +09:00
|
|
|
export type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";
|
2025-10-02 17:19:39 +09:00
|
|
|
|
2025-10-21 11:44:06 +09:00
|
|
|
export type PathParams = Record<string, string | number>;
|
2025-10-02 18:35:26 +09:00
|
|
|
export type QueryPrimitive = string | number | boolean;
|
|
|
|
|
export type QueryParams = Record<
|
2025-10-02 17:19:39 +09:00
|
|
|
string,
|
|
|
|
|
QueryPrimitive | QueryPrimitive[] | readonly QueryPrimitive[] | undefined
|
|
|
|
|
>;
|
|
|
|
|
|
|
|
|
|
export interface RequestOptions {
|
|
|
|
|
params?: {
|
|
|
|
|
path?: PathParams;
|
|
|
|
|
query?: QueryParams;
|
|
|
|
|
};
|
|
|
|
|
body?: unknown;
|
|
|
|
|
headers?: Record<string, string>;
|
|
|
|
|
signal?: AbortSignal;
|
|
|
|
|
credentials?: RequestCredentials;
|
|
|
|
|
disableCsrf?: boolean;
|
|
|
|
|
}
|
2025-09-19 12:58:00 +09:00
|
|
|
|
2025-10-02 17:19:39 +09:00
|
|
|
export type AuthHeaderResolver = () => string | undefined;
|
2025-09-19 12:58:00 +09:00
|
|
|
|
2025-10-02 17:19:39 +09:00
|
|
|
export interface CreateClientOptions {
|
|
|
|
|
baseUrl?: string;
|
|
|
|
|
getAuthHeader?: AuthHeaderResolver;
|
|
|
|
|
handleError?: (response: Response) => void | Promise<void>;
|
|
|
|
|
enableCsrf?: boolean;
|
|
|
|
|
}
|
2025-09-17 18:43:43 +09:00
|
|
|
|
2025-10-02 17:19:39 +09:00
|
|
|
type ApiMethod = <T = unknown>(path: string, options?: RequestOptions) => Promise<ApiResponse<T>>;
|
|
|
|
|
|
|
|
|
|
export interface ApiClient {
|
|
|
|
|
GET: ApiMethod;
|
|
|
|
|
POST: ApiMethod;
|
|
|
|
|
PUT: ApiMethod;
|
|
|
|
|
PATCH: ApiMethod;
|
|
|
|
|
DELETE: ApiMethod;
|
|
|
|
|
}
|
2025-09-18 16:23:56 +09:00
|
|
|
|
2025-09-19 12:58:00 +09:00
|
|
|
type EnvKey =
|
|
|
|
|
| "NEXT_PUBLIC_API_BASE"
|
|
|
|
|
| "NEXT_PUBLIC_API_URL"
|
|
|
|
|
| "API_BASE_URL"
|
|
|
|
|
| "API_BASE"
|
|
|
|
|
| "API_URL";
|
|
|
|
|
|
|
|
|
|
const BASE_URL_ENV_KEYS: readonly EnvKey[] = [
|
|
|
|
|
"NEXT_PUBLIC_API_BASE",
|
|
|
|
|
"NEXT_PUBLIC_API_URL",
|
|
|
|
|
"API_BASE_URL",
|
|
|
|
|
"API_BASE",
|
|
|
|
|
"API_URL",
|
|
|
|
|
];
|
|
|
|
|
|
2025-09-27 16:59:25 +09:00
|
|
|
const DEFAULT_BASE_URL = "http://localhost:4000";
|
2025-09-19 12:58:00 +09:00
|
|
|
|
|
|
|
|
const normalizeBaseUrl = (value: string) => {
|
|
|
|
|
const trimmed = value.trim();
|
|
|
|
|
if (!trimmed) {
|
|
|
|
|
return DEFAULT_BASE_URL;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (trimmed === "/") {
|
|
|
|
|
return trimmed;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return trimmed.replace(/\/+$/, "");
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const resolveBaseUrlFromEnv = () => {
|
2025-09-26 18:28:47 +09:00
|
|
|
if (typeof process !== "undefined" && process.env) {
|
|
|
|
|
for (const key of BASE_URL_ENV_KEYS) {
|
|
|
|
|
const envValue = process.env[key];
|
|
|
|
|
if (typeof envValue === "string" && envValue.trim()) {
|
|
|
|
|
return normalizeBaseUrl(envValue);
|
|
|
|
|
}
|
2025-09-19 12:58:00 +09:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return DEFAULT_BASE_URL;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const resolveBaseUrl = (baseUrl?: string) => {
|
|
|
|
|
if (typeof baseUrl === "string" && baseUrl.trim()) {
|
|
|
|
|
return normalizeBaseUrl(baseUrl);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return resolveBaseUrlFromEnv();
|
|
|
|
|
};
|
|
|
|
|
|
2025-10-02 17:19:39 +09:00
|
|
|
const applyPathParams = (path: string, params?: PathParams): string => {
|
|
|
|
|
if (!params) {
|
|
|
|
|
return path;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return path.replace(/\{([^}]+)\}/g, (_match, rawKey) => {
|
|
|
|
|
const key = rawKey as keyof typeof params;
|
|
|
|
|
|
|
|
|
|
if (!(key in params)) {
|
|
|
|
|
throw new Error(`Missing path parameter: ${String(rawKey)}`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const value = params[key];
|
|
|
|
|
return encodeURIComponent(String(value));
|
|
|
|
|
});
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const buildQueryString = (query?: QueryParams): string => {
|
|
|
|
|
if (!query) {
|
|
|
|
|
return "";
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const searchParams = new URLSearchParams();
|
|
|
|
|
|
|
|
|
|
const appendPrimitive = (key: string, value: QueryPrimitive) => {
|
|
|
|
|
searchParams.append(key, String(value));
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
for (const [key, value] of Object.entries(query)) {
|
|
|
|
|
if (value === undefined || value === null) {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (Array.isArray(value)) {
|
2025-10-02 18:35:26 +09:00
|
|
|
(value as readonly QueryPrimitive[]).forEach(entry => appendPrimitive(key, entry));
|
2025-10-02 17:19:39 +09:00
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-02 18:35:26 +09:00
|
|
|
appendPrimitive(key, value as QueryPrimitive);
|
2025-10-02 17:19:39 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return searchParams.toString();
|
|
|
|
|
};
|
2025-09-19 12:57:39 +09:00
|
|
|
|
2025-09-25 18:59:07 +09:00
|
|
|
const getBodyMessage = (body: unknown): string | null => {
|
|
|
|
|
if (typeof body === "string") {
|
|
|
|
|
return body;
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-02 17:19:39 +09:00
|
|
|
if (body && typeof body === "object" && "message" in body) {
|
2025-09-25 18:59:07 +09:00
|
|
|
const maybeMessage = (body as { message?: unknown }).message;
|
|
|
|
|
if (typeof maybeMessage === "string") {
|
|
|
|
|
return maybeMessage;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return null;
|
|
|
|
|
};
|
|
|
|
|
|
2025-09-19 12:57:39 +09:00
|
|
|
async function defaultHandleError(response: Response) {
|
|
|
|
|
if (response.ok) return;
|
|
|
|
|
|
|
|
|
|
let body: unknown;
|
|
|
|
|
let message = response.statusText || `Request failed with status ${response.status}`;
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const cloned = response.clone();
|
|
|
|
|
const contentType = cloned.headers.get("content-type");
|
|
|
|
|
if (contentType?.includes("application/json")) {
|
|
|
|
|
body = await cloned.json();
|
2025-09-25 18:59:07 +09:00
|
|
|
const jsonMessage = getBodyMessage(body);
|
|
|
|
|
if (jsonMessage) {
|
|
|
|
|
message = jsonMessage;
|
2025-09-19 12:57:39 +09:00
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
const text = await cloned.text();
|
|
|
|
|
if (text) {
|
|
|
|
|
body = text;
|
|
|
|
|
message = text;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
} catch {
|
|
|
|
|
// Ignore body parse errors; fall back to status text
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
throw new ApiError(message, response, body);
|
2025-09-17 18:43:43 +09:00
|
|
|
}
|
|
|
|
|
|
2025-10-02 17:19:39 +09:00
|
|
|
const parseResponseBody = async (response: Response): Promise<unknown> => {
|
|
|
|
|
if (response.status === 204) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const contentLength = response.headers.get("content-length");
|
|
|
|
|
if (contentLength === "0") {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const contentType = response.headers.get("content-type") ?? "";
|
|
|
|
|
|
|
|
|
|
if (contentType.includes("application/json")) {
|
|
|
|
|
try {
|
|
|
|
|
return await response.json();
|
|
|
|
|
} catch {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (contentType.includes("text/")) {
|
|
|
|
|
try {
|
|
|
|
|
return await response.text();
|
|
|
|
|
} catch {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return null;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
interface CsrfTokenPayload {
|
|
|
|
|
success: boolean;
|
|
|
|
|
token: string;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const isCsrfTokenPayload = (value: unknown): value is CsrfTokenPayload => {
|
|
|
|
|
return (
|
|
|
|
|
typeof value === "object" &&
|
|
|
|
|
value !== null &&
|
|
|
|
|
"success" in value &&
|
|
|
|
|
"token" in value &&
|
|
|
|
|
typeof (value as { success: unknown }).success === "boolean" &&
|
|
|
|
|
typeof (value as { token: unknown }).token === "string"
|
|
|
|
|
);
|
|
|
|
|
};
|
|
|
|
|
|
2025-09-27 16:59:25 +09:00
|
|
|
class CsrfTokenManager {
|
|
|
|
|
private token: string | null = null;
|
|
|
|
|
private tokenPromise: Promise<string> | null = null;
|
|
|
|
|
|
2025-10-02 17:19:39 +09:00
|
|
|
constructor(private readonly baseUrl: string) {}
|
2025-09-27 16:59:25 +09:00
|
|
|
|
|
|
|
|
async getToken(): Promise<string> {
|
|
|
|
|
if (this.token) {
|
|
|
|
|
return this.token;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (this.tokenPromise) {
|
|
|
|
|
return this.tokenPromise;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
this.tokenPromise = this.fetchToken();
|
|
|
|
|
try {
|
|
|
|
|
this.token = await this.tokenPromise;
|
|
|
|
|
return this.token;
|
|
|
|
|
} finally {
|
|
|
|
|
this.tokenPromise = null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-02 17:19:39 +09:00
|
|
|
clearToken(): void {
|
|
|
|
|
this.token = null;
|
|
|
|
|
this.tokenPromise = null;
|
|
|
|
|
}
|
|
|
|
|
|
2025-09-27 16:59:25 +09:00
|
|
|
private async fetchToken(): Promise<string> {
|
|
|
|
|
const response = await fetch(`${this.baseUrl}/api/security/csrf/token`, {
|
2025-09-29 13:36:40 +09:00
|
|
|
method: "GET",
|
|
|
|
|
credentials: "include",
|
2025-09-27 16:59:25 +09:00
|
|
|
headers: {
|
2025-09-29 13:36:40 +09:00
|
|
|
Accept: "application/json",
|
2025-09-27 16:59:25 +09:00
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!response.ok) {
|
|
|
|
|
throw new Error(`Failed to fetch CSRF token: ${response.status}`);
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-02 17:19:39 +09:00
|
|
|
const data: unknown = await response.json();
|
|
|
|
|
if (!isCsrfTokenPayload(data)) {
|
2025-09-29 13:36:40 +09:00
|
|
|
throw new Error("Invalid CSRF token response");
|
2025-09-27 16:59:25 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return data.token;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-02 17:19:39 +09:00
|
|
|
const SAFE_METHODS = new Set<HttpMethod>(["GET", "HEAD", "OPTIONS"]);
|
|
|
|
|
|
2025-09-19 12:58:00 +09:00
|
|
|
export function createClient(options: CreateClientOptions = {}): ApiClient {
|
|
|
|
|
const baseUrl = resolveBaseUrl(options.baseUrl);
|
2025-10-02 17:19:39 +09:00
|
|
|
const resolveAuthHeader = options.getAuthHeader;
|
2025-09-19 12:57:39 +09:00
|
|
|
const handleError = options.handleError ?? defaultHandleError;
|
2025-09-27 16:59:25 +09:00
|
|
|
const enableCsrf = options.enableCsrf ?? true;
|
|
|
|
|
const csrfManager = enableCsrf ? new CsrfTokenManager(baseUrl) : null;
|
2025-09-18 16:00:20 +09:00
|
|
|
|
2025-10-02 17:19:39 +09:00
|
|
|
const request = async <T>(
|
|
|
|
|
method: HttpMethod,
|
|
|
|
|
path: string,
|
|
|
|
|
opts: RequestOptions = {}
|
|
|
|
|
): Promise<ApiResponse<T>> => {
|
|
|
|
|
const resolvedPath = applyPathParams(path, opts.params?.path);
|
|
|
|
|
const url = new URL(resolvedPath, baseUrl);
|
|
|
|
|
|
|
|
|
|
const queryString = buildQueryString(opts.params?.query);
|
|
|
|
|
if (queryString) {
|
|
|
|
|
url.search = queryString;
|
|
|
|
|
}
|
2025-09-18 16:23:56 +09:00
|
|
|
|
2025-10-02 17:19:39 +09:00
|
|
|
const headers = new Headers(opts.headers);
|
2025-09-29 13:36:40 +09:00
|
|
|
|
2025-10-02 17:19:39 +09:00
|
|
|
const credentials = opts.credentials ?? "include";
|
|
|
|
|
const init: RequestInit = {
|
|
|
|
|
method,
|
|
|
|
|
headers,
|
|
|
|
|
credentials,
|
|
|
|
|
signal: opts.signal,
|
2025-09-19 12:58:00 +09:00
|
|
|
};
|
|
|
|
|
|
2025-10-02 17:19:39 +09:00
|
|
|
const body = opts.body;
|
|
|
|
|
if (body !== undefined && body !== null) {
|
|
|
|
|
if (body instanceof FormData || body instanceof Blob) {
|
|
|
|
|
init.body = body as BodyInit;
|
|
|
|
|
} else {
|
|
|
|
|
if (!headers.has("Content-Type")) {
|
|
|
|
|
headers.set("Content-Type", "application/json");
|
|
|
|
|
}
|
|
|
|
|
init.body = JSON.stringify(body);
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-09-26 15:51:07 +09:00
|
|
|
|
2025-10-02 17:19:39 +09:00
|
|
|
if (resolveAuthHeader && !headers.has("Authorization")) {
|
|
|
|
|
const headerValue = resolveAuthHeader();
|
|
|
|
|
if (headerValue) {
|
|
|
|
|
headers.set("Authorization", headerValue);
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-09-27 16:59:25 +09:00
|
|
|
|
2025-10-02 17:19:39 +09:00
|
|
|
if (
|
|
|
|
|
csrfManager &&
|
|
|
|
|
!opts.disableCsrf &&
|
|
|
|
|
!SAFE_METHODS.has(method) &&
|
|
|
|
|
!headers.has("X-CSRF-Token")
|
|
|
|
|
) {
|
|
|
|
|
try {
|
|
|
|
|
const csrfToken = await csrfManager.getToken();
|
|
|
|
|
headers.set("X-CSRF-Token", csrfToken);
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.warn("Failed to obtain CSRF token", error);
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-09-26 15:51:07 +09:00
|
|
|
|
2025-10-02 17:19:39 +09:00
|
|
|
const response = await fetch(url.toString(), init);
|
2025-09-26 15:51:07 +09:00
|
|
|
|
2025-10-02 17:19:39 +09:00
|
|
|
if (!response.ok) {
|
|
|
|
|
if (response.status === 403 && csrfManager) {
|
|
|
|
|
try {
|
|
|
|
|
const bodyText = await response.clone().text();
|
|
|
|
|
if (bodyText.toLowerCase().includes("csrf")) {
|
|
|
|
|
csrfManager.clearToken();
|
|
|
|
|
}
|
|
|
|
|
} catch {
|
|
|
|
|
csrfManager.clearToken();
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-09-26 15:51:07 +09:00
|
|
|
|
2025-10-02 17:19:39 +09:00
|
|
|
await handleError(response);
|
|
|
|
|
// If handleError does not throw, throw a default error to ensure rejection
|
|
|
|
|
throw new ApiError(`Request failed with status ${response.status}`, response);
|
|
|
|
|
}
|
2025-09-26 15:51:07 +09:00
|
|
|
|
2025-10-02 17:19:39 +09:00
|
|
|
const parsedBody = await parseResponseBody(response);
|
2025-09-26 15:51:07 +09:00
|
|
|
|
2025-10-21 11:44:06 +09:00
|
|
|
if (parsedBody === undefined || parsedBody === null) {
|
|
|
|
|
return {};
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-02 17:19:39 +09:00
|
|
|
return {
|
2025-10-21 11:44:06 +09:00
|
|
|
data: parsedBody as T,
|
2025-10-02 17:19:39 +09:00
|
|
|
};
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
GET: (path, opts) => request("GET", path, opts),
|
|
|
|
|
POST: (path, opts) => request("POST", path, opts),
|
|
|
|
|
PUT: (path, opts) => request("PUT", path, opts),
|
|
|
|
|
PATCH: (path, opts) => request("PATCH", path, opts),
|
|
|
|
|
DELETE: (path, opts) => request("DELETE", path, opts),
|
|
|
|
|
} satisfies ApiClient;
|
2025-09-18 16:23:56 +09:00
|
|
|
}
|