import {z} from 'zod' export type GetApiCellarAccountsAccountIDBottlesArgs = {accountID: number, years?: Array | undefined}; export type GetApiCellarAccountsAccountIDBottlesOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const accountTiny = z.object({href: z.string(), id: z.number().int(), name: z.string()}); export const accountLink = z.object({href: z.string(), id: z.number().int()}); export const bottleLinks = z.object({account: accountLink.optional()}); export const bottle = z.object({account: accountTiny.optional(), href: z.string(), id: z.number().int(), links: bottleLinks.optional(), name: z.string().min(2), rating: z.number().int().gte(1).lte(5).optional(), varietal: z.string().min(4), vineyard: z.string().min(2), vintage: z.number().int().gte(1900).lte(2020)}); export const bottleCollection = z.array(bottle); 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 }; /** * list bottle * * GET /cellar/accounts/{accountID}/bottles */ export const getApiCellarAccountsAccountIDBottles = async (args: GetApiCellarAccountsAccountIDBottlesArgs, options?: GetApiCellarAccountsAccountIDBottlesOptions) => { const {baseUrl = "http://localhost:8081", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/vnd.bottle+json; type=collection") for (const item of args.years ?? []) query.append("years", String(item)) const url = `${baseUrl.replace(/\/+$/, '')}/cellar/accounts/${encodeURIComponent(String(args.accountID))}/bottles${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(bottleCollection, await res.json()) };