feat: add typed immich api adapter

This commit is contained in:
Leon Tonhäuser committed 2026-08-09 21:39:12 +02:00
1 parent b84562ad52
commit a5973bfaf1
7 files changed
+735 -7

No files matched your search

+220
View File
@@ -0,0 +1,220 @@
import "server-only";
import { z } from "zod";
import { env } from "@/config/env";
import { ImmichClientError, type ImmichErrorCode } from "./errors";
import type {
ImmichAlbum,
ImmichAlbumSummary,
ImmichAsset,
ImmichBinary,
ImmichClient,
ImmichSearchPage,
} from "./types";
const nullableString = z.string().nullable().optional().transform((value) => value ?? null);
const assetSchema = z
.object({
id: z.string(),
type: z.literal("IMAGE"),
originalFileName: z.string(),
originalMimeType: z.string(),
localDateTime: nullableString,
fileCreatedAt: nullableString,
albums: z.array(z.object({ id: z.string() }).passthrough()).optional().default([]),
})
.passthrough();
const albumSummarySchema = z
.object({
id: z.string(),
albumName: z.string(),
description: nullableString,
albumThumbnailAssetId: nullableString,
assetCount: z.number().int().nonnegative(),
})
.passthrough();
const albumSchema = albumSummarySchema.extend({
assets: z.array(assetSchema),
});
const metadataSearchSchema = z
.object({
assets: z
.object({
items: z.array(assetSchema),
total: z.number().int().nonnegative(),
nextPage: z.number().int().nullable().optional().transform((value) => value ?? null),
previousPage: z.number().int().nullable().optional().transform((value) => value ?? null),
})
.passthrough(),
})
.passthrough();
type FetchLike = typeof globalThis.fetch;
export type CreateImmichClientOptions = {
baseUrl?: string;
apiKey?: string;
fetch?: FetchLike;
timeoutMs?: number;
};
function errorForStatus(status: number): ImmichClientError {
const code: ImmichErrorCode =
status === 401 || status === 403
? "IMMICH_AUTH_FAILED"
: status === 404
? "IMMICH_NOT_FOUND"
: status === 429
? "IMMICH_RATE_LIMITED"
: status >= 500
? "IMMICH_UNAVAILABLE"
: "IMMICH_REQUEST_FAILED";
return new ImmichClientError(code, status);
}
function responseFilename(response: Response, fallback: string): string {
const contentDisposition = response.headers.get("content-disposition");
const match = contentDisposition?.match(/filename\*?=(?:UTF-8''|\")(.*?)(?:\"|;|$)/i);
const filename = match?.[1]?.trim();
if (!filename) {
return fallback;
}
try {
return decodeURIComponent(filename);
} catch {
return filename;
}
}
function contentLength(response: Response): number | null {
const value = response.headers.get("content-length");
if (!value || !/^\d+$/.test(value)) {
return null;
}
const length = Number(value);
return Number.isSafeInteger(length) ? length : null;
}
export function createImmichClient({
baseUrl = env.IMMICH_BASE_URL,
apiKey = env.IMMICH_API_KEY,
fetch: fetchImpl,
timeoutMs = 15_000,
}: CreateImmichClientOptions = {}): ImmichClient {
const apiBaseUrl = `${baseUrl.replace(/\/+$/, "")}/api`;
async function request(path: string, init: RequestInit, signal?: AbortSignal): Promise<Response> {
const timeoutSignal = AbortSignal.timeout(timeoutMs);
const requestSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
let response: Response;
try {
response = await (fetchImpl ?? globalThis.fetch)(`${apiBaseUrl}${path}`, {
...init,
headers: {
"x-api-key": apiKey,
...init.headers,
},
signal: requestSignal,
});
} catch {
if (timeoutSignal.aborted) {
throw new ImmichClientError("IMMICH_TIMEOUT");
}
if (signal?.aborted) {
throw new ImmichClientError("IMMICH_ABORTED");
}
throw new ImmichClientError("IMMICH_UNAVAILABLE");
}
if (!response.ok) {
throw errorForStatus(response.status);
}
return response;
}
async function requestJson<T>(
path: string,
init: RequestInit,
schema: z.ZodType<T>,
signal?: AbortSignal,
): Promise<T> {
const response = await request(path, init, signal);
try {
return schema.parse(await response.json());
} catch {
throw new ImmichClientError("IMMICH_INVALID_RESPONSE");
}
}
async function requestBinary(path: string, signal?: AbortSignal): Promise<ImmichBinary> {
const response = await request(path, { method: "GET" }, signal);
if (!response.body) {
throw new ImmichClientError("IMMICH_INVALID_RESPONSE");
}
return {
body: response.body,
contentType: response.headers.get("content-type") ?? "application/octet-stream",
contentLength: contentLength(response),
filename: responseFilename(response, "asset"),
};
}
return {
listAlbums(signal) {
return requestJson<ImmichAlbumSummary[]>("/albums", { method: "GET" }, z.array(albumSummarySchema), signal);
},
getAlbum(albumId, signal) {
return requestJson<ImmichAlbum>(
`/albums/${encodeURIComponent(albumId)}`,
{ method: "GET" },
albumSchema,
signal,
);
},
searchPhotos(input, signal) {
return requestJson<ImmichSearchPage>(
"/search/metadata",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
albumIds: input.albumIds,
...(input.description === undefined ? {} : { description: input.description }),
type: "IMAGE",
page: input.page,
size: input.size,
}),
},
metadataSearchSchema.transform(({ assets }) => ({
items: assets.items,
total: assets.total,
nextPage: assets.nextPage,
previousPage: assets.previousPage,
})),
signal,
);
},
getThumbnail(assetId, signal) {
return requestBinary(`/assets/${encodeURIComponent(assetId)}/thumbnail`, signal);
},
getOriginal(assetId, signal) {
return requestBinary(`/assets/${encodeURIComponent(assetId)}/original`, signal);
},
};
}
export const immichClient = createImmichClient();