import {z} from 'zod' export type GetApiImagesArgs = {tagged?: (boolean | null) | undefined}; export type GetApiImagesOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const metadataModel = z.object({name: z.string(), date_created: z.string().nullable(), width: z.number().int(), height: z.number().int(), file_location: z.string(), file_size: z.number().int(), item_type: z.string(), latitude: z.number().nullable().optional(), longitude: z.number().nullable().optional(), location: z.string().nullable().optional()}); export const imageData = z.object({id: z.string(), path: z.string(), folder_id: z.string(), thumbnailPath: z.string(), metadata: metadataModel, isTagged: z.boolean(), isFavourite: z.boolean(), favouritedAt: z.string().nullable().optional(), tags: z.array(z.string()).nullable().optional()}); export const getAllImagesResponse = z.object({success: z.boolean(), message: z.string(), data: z.array(imageData)}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Get All Images * * GET /images/ */ export const getApiImages = async (args: GetApiImagesArgs, options?: GetApiImagesOptions) => { const {baseUrl = "http://localhost:52123", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.tagged != null) query.append("tagged", String(args.tagged)) const url = `${baseUrl.replace(/\/+$/, '')}/images/${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(getAllImagesResponse, await res.json()) };