import {z} from 'zod' export type CreateApiFoodIngredientsGlycemicLoadArgs = {language?: ('en' | 'de') | undefined, body: {ingredients: Array}}; export type CreateApiFoodIngredientsGlycemicLoadOptions = {baseUrl?: string | undefined, apiKeyScheme?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiFoodIngredientsGlycemicLoadResponse = z.object({totalGlycemicLoad: z.number(), ingredients: z.array(z.object({id: z.number().int(), original: z.string().min(1), glycemicIndex: z.number(), glycemicLoad: z.number()}))}); 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 }; /** * Compute Glycemic Load * * POST /food/ingredients/glycemicLoad */ export const createApiFoodIngredientsGlycemicLoad = async (args: CreateApiFoodIngredientsGlycemicLoadArgs, options?: CreateApiFoodIngredientsGlycemicLoadOptions) => { const {baseUrl = "https://api.spoonacular.com", fetch: fetchFn = fetch, apiKeyScheme} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.language != null) query.append("language", String(args.language)) if (apiKeyScheme !== undefined) headers.set("x-api-key", apiKeyScheme) const url = `${baseUrl.replace(/\/+$/, '')}/food/ingredients/glycemicLoad${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(createApiFoodIngredientsGlycemicLoadResponse, await res.json()) };