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

+146
View File
@@ -0,0 +1,146 @@
import { afterEach, beforeEach, expect, test } from "vitest";
import { HttpResponse, http } from "msw";
import { setupServer } from "msw/node";
import { createImmichClient } from "./client";
import {
immichAlbum,
immichAlbumDetail,
immichMetadataSearchResponse,
} from "../../../tests/fixtures/immich";
const baseUrl = "http://immich.test";
const apiKey = "test-api-key";
const server = setupServer();
const client = createImmichClient({ baseUrl, apiKey, timeoutMs: 1_000 });
beforeEach(() => server.listen({ onUnhandledRequest: "error" }));
afterEach(() => server.resetHandlers());
afterEach(() => server.close());
test("lists albums through the documented API with server-side authentication", async () => {
server.use(
http.get(`${baseUrl}/api/albums`, ({ request }) => {
expect(request.headers.get("x-api-key")).toBe(apiKey);
expect(request.headers.get("authorization")).toBeNull();
return HttpResponse.json([immichAlbum]);
}),
);
await expect(client.listAlbums()).resolves.toEqual([immichAlbum]);
});
test("gets album details from the documented album endpoint", async () => {
server.use(
http.get(`${baseUrl}/api/albums/album-1`, ({ request }) => {
expect(request.method).toBe("GET");
expect(request.headers.get("x-api-key")).toBe(apiKey);
return HttpResponse.json(immichAlbumDetail);
}),
);
await expect(client.getAlbum("album-1")).resolves.toEqual(immichAlbumDetail);
});
test("forces IMAGE and authorized album IDs in metadata search", async () => {
server.use(
http.post(`${baseUrl}/api/search/metadata`, async ({ request }) => {
expect(request.method).toBe("POST");
expect(request.headers.get("x-api-key")).toBe(apiKey);
expect(request.headers.get("content-type")).toBe("application/json");
await expect(request.json()).resolves.toEqual({
albumIds: ["album-1"],
description: "jubel",
type: "IMAGE",
page: 1,
size: 60,
});
return HttpResponse.json(immichMetadataSearchResponse);
}),
);
await expect(
client.searchPhotos({ albumIds: ["album-1"], description: "jubel", page: 1, size: 60 }),
).resolves.toEqual({
items: immichMetadataSearchResponse.assets.items,
total: 1,
nextPage: null,
previousPage: null,
});
});
test("maps an Immich outage to IMMICH_UNAVAILABLE", async () => {
server.use(http.get(`${baseUrl}/api/albums`, () => HttpResponse.error()));
await expect(client.listAlbums()).rejects.toMatchObject({ code: "IMMICH_UNAVAILABLE" });
});
test("maps upstream authorization, missing, rate-limit, server, and malformed failures", async () => {
server.use(http.get(`${baseUrl}/api/albums`, () => new HttpResponse(null, { status: 401 })));
await expect(client.listAlbums()).rejects.toMatchObject({ code: "IMMICH_AUTH_FAILED" });
server.use(http.get(`${baseUrl}/api/albums`, () => new HttpResponse(null, { status: 403 })));
await expect(client.listAlbums()).rejects.toMatchObject({ code: "IMMICH_AUTH_FAILED" });
server.use(http.get(`${baseUrl}/api/albums/hidden`, () => new HttpResponse(null, { status: 404 })));
await expect(client.getAlbum("hidden")).rejects.toMatchObject({ code: "IMMICH_NOT_FOUND" });
server.use(http.get(`${baseUrl}/api/albums`, () => new HttpResponse(null, { status: 429 })));
await expect(client.listAlbums()).rejects.toMatchObject({ code: "IMMICH_RATE_LIMITED" });
server.use(http.get(`${baseUrl}/api/albums`, () => new HttpResponse(null, { status: 503 })));
await expect(client.listAlbums()).rejects.toMatchObject({ code: "IMMICH_UNAVAILABLE" });
server.use(http.get(`${baseUrl}/api/albums`, () => HttpResponse.json([{ id: "malformed" }])));
await expect(client.listAlbums()).rejects.toMatchObject({ code: "IMMICH_INVALID_RESPONSE" });
});
test("maps an aborted timeout signal to IMMICH_TIMEOUT", async () => {
const timedOutClient = createImmichClient({
baseUrl,
apiKey,
timeoutMs: 1,
fetch: (_input, init) =>
new Promise((_resolve, reject) => {
init?.signal?.addEventListener("abort", () => reject(init.signal?.reason));
}),
});
await expect(timedOutClient.listAlbums()).rejects.toMatchObject({ code: "IMMICH_TIMEOUT" });
});
test("streams binary endpoints without buffering and preserves safe response metadata", async () => {
const bytes = new Uint8Array([1, 2, 3]);
server.use(
http.get(`${baseUrl}/api/assets/asset-1/thumbnail`, ({ request }) => {
expect(request.method).toBe("GET");
expect(request.headers.get("x-api-key")).toBe(apiKey);
return new HttpResponse(bytes, {
headers: {
"content-type": "image/jpeg",
"content-length": "3",
"content-disposition": 'inline; filename="jubel.jpg"',
},
});
}),
http.get(`${baseUrl}/api/assets/asset-1/original`, ({ request }) => {
expect(request.method).toBe("GET");
expect(request.headers.get("x-api-key")).toBe(apiKey);
return new HttpResponse(bytes, {
headers: {
"content-type": "image/jpeg",
"content-length": "3",
"content-disposition": 'attachment; filename="jubel.jpg"',
},
});
}),
);
const thumbnail = await client.getThumbnail("asset-1");
expect(thumbnail).toMatchObject({ contentType: "image/jpeg", contentLength: 3, filename: "jubel.jpg" });
await expect(new Response(thumbnail.body).arrayBuffer()).resolves.toEqual(bytes.buffer);
const original = await client.getOriginal("asset-1");
expect(original).toMatchObject({ contentType: "image/jpeg", contentLength: 3, filename: "jubel.jpg" });
await expect(new Response(original.body).arrayBuffer()).resolves.toEqual(bytes.buffer);
});
+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();
+34
View File
@@ -0,0 +1,34 @@
export const IMMICH_ERROR_CODES = [
"IMMICH_AUTH_FAILED",
"IMMICH_NOT_FOUND",
"IMMICH_RATE_LIMITED",
"IMMICH_TIMEOUT",
"IMMICH_ABORTED",
"IMMICH_UNAVAILABLE",
"IMMICH_INVALID_RESPONSE",
"IMMICH_REQUEST_FAILED",
] as const;
export type ImmichErrorCode = (typeof IMMICH_ERROR_CODES)[number];
const errorMessages: Record<ImmichErrorCode, string> = {
IMMICH_AUTH_FAILED: "Immich authentication failed",
IMMICH_NOT_FOUND: "Immich resource not found",
IMMICH_RATE_LIMITED: "Immich rate limit exceeded",
IMMICH_TIMEOUT: "Immich request timed out",
IMMICH_ABORTED: "Immich request aborted",
IMMICH_UNAVAILABLE: "Immich is unavailable",
IMMICH_INVALID_RESPONSE: "Immich returned an invalid response",
IMMICH_REQUEST_FAILED: "Immich request failed",
};
export class ImmichClientError extends Error {
readonly name = "ImmichClientError";
constructor(
readonly code: ImmichErrorCode,
readonly status?: number,
) {
super(errorMessages[code]);
}
}
+46
View File
@@ -0,0 +1,46 @@
export type ImmichAlbumSummary = {
id: string;
albumName: string;
description: string | null;
albumThumbnailAssetId: string | null;
assetCount: number;
};
export type ImmichAsset = {
id: string;
type: "IMAGE";
originalFileName: string;
originalMimeType: string;
localDateTime: string | null;
fileCreatedAt: string | null;
albums: Array<{ id: string }>;
};
export type ImmichAlbum = ImmichAlbumSummary & {
assets: ImmichAsset[];
};
export type ImmichSearchPage = {
items: ImmichAsset[];
total: number;
nextPage: number | null;
previousPage: number | null;
};
export type ImmichBinary = {
body: ReadableStream<Uint8Array>;
contentType: string;
contentLength: number | null;
filename: string;
};
export interface ImmichClient {
listAlbums(signal?: AbortSignal): Promise<ImmichAlbumSummary[]>;
getAlbum(albumId: string, signal?: AbortSignal): Promise<ImmichAlbum>;
searchPhotos(
input: { albumIds: string[]; description?: string; page: number; size: number },
signal?: AbortSignal,
): Promise<ImmichSearchPage>;
getThumbnail(assetId: string, signal?: AbortSignal): Promise<ImmichBinary>;
getOriginal(assetId: string, signal?: AbortSignal): Promise<ImmichBinary>;
}