import {z} from 'zod' export type GetApiBagsArgs = {shoppingDate: string}; export type GetApiBagsOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const bagType = z.enum(["REGULAR", "VALUE"]); export const priceAvailability = z.object({startDate: z.string(), endDate: z.string()}); export const price = z.object({promo: z.boolean(), value: z.number(), originalValue: z.number().nullable(), availability: priceAvailability.nullable().optional()}); export const bag = z.object({id: z.number().int(), erpItemId: z.number().int(), name: z.string(), shortName: z.string(), bagType: bagType, description: z.string(), shortDescription: z.string(), contentsProfile: z.string(), contentsDescription: z.string(), portionText: z.string(), portionSize: z.number().int(), uri: z.string(), imageUrl: z.string(), price: price, customizationFee: z.number(), points: z.number().int().nullable(), allowExtraItems: z.boolean(), extraBagPointPrice: z.number(), published: z.boolean(), immutable: z.boolean(), allowedIntervals: z.array(z.number().int()), allowedCategoryCodes: z.array(z.string()), isDIY: z.boolean(), isFeatured: z.boolean(), isOrganic: z.boolean()}); export const getApiBagsResponse = z.array(bag); 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 /bags */ export const getApiBags = async (args: GetApiBagsArgs, options: GetApiBagsOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.shoppingDate != null) query.append("shoppingDate", String(args.shoppingDate)) const url = `${baseUrl.replace(/\/+$/, '')}/bags${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(getApiBagsResponse, await res.json()) };