import {z} from 'zod' export type KeysetSeek = 'BEFORE' | 'AFTER'; export type InventoryRuleKeyset = {seek?: (KeysetSeek | null) | undefined, size?: (number | null) | undefined, ruleId?: (number | null) | undefined, endDate?: (string | null) | undefined}; export type GetApiInventoryRulesArgs = {productId: number, withDemand?: (boolean | null) | undefined, keyset: InventoryRuleKeyset}; export type GetApiInventoryRulesOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const keysetSeek = z.enum(["BEFORE", "AFTER"]); export const inventoryRuleKeyset = z.object({seek: keysetSeek.nullable().optional(), size: z.number().int().gte(0).lte(50).nullable().optional(), ruleId: z.number().int().nullable().optional(), endDate: z.string().nullable().optional()}); export const keysetPageObjectInventoryRuleKeyset = z.object({data: z.array(z.object({})), previousKeyset: inventoryRuleKeyset.nullable(), nextKeyset: inventoryRuleKeyset.nullable()}); 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 /inventory-rules */ export const getApiInventoryRules = async (args: GetApiInventoryRulesArgs, options: GetApiInventoryRulesOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.productId != null) query.append("productId", String(args.productId)) if (args.withDemand != null) query.append("withDemand", String(args.withDemand)) if (args.keyset != null) query.append("keyset", JSON.stringify(args.keyset)) const url = `${baseUrl.replace(/\/+$/, '')}/inventory-rules${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(keysetPageObjectInventoryRuleKeyset, await res.json()) };