import {z} from 'zod' export type GetApiWsListingsDetailOptions = {baseUrl?: string | undefined, ApiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const listingStateValue = z.union([z.literal(9), z.literal(0), z.literal(1), z.literal(2), z.literal(3), z.literal(4)]); export const aestheticGradeValue = z.enum(["PREMIUM", "EXCELLENT", "VERY_GOOD", "GOOD", "FAIR", "STALLONE"]); export const getApiWsListingsDetailResponse = z.object({backmarket_id: z.number().int(), comment: z.string().nullable(), currency: z.string(), id: z.string(), listing_id: z.number().int(), max_price: z.string(), min_price: z.string().nullable(), price: z.string(), product_id: z.string(), publication_state: z.union([z.literal(0), z.literal(1), z.literal(2), z.literal(3), z.literal(4)]), quantity: z.number().int(), shippings: z.array(z.object({country_code: z.string(), shipper: z.string(), shipper_display: z.string(), shipping_delay: z.number().int(), shipping_price: z.string()})), sku: z.string(), state: listingStateValue, grade: aestheticGradeValue, title: z.string(), warranty_delay: z.number().int(), new_battery: z.boolean().optional(), outlet: z.boolean().optional(), statuscode: z.number().int()}); 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 listing details * * GET /ws/listings/detail * * Also accepts auth: BasicAuth */ export const getApiWsListingsDetail = async (options?: GetApiWsListingsDetailOptions) => { const {baseUrl = "https://preprod.backmarket.co.jp", fetch: fetchFn = fetch, ApiKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (ApiKeyAuth !== undefined) headers.set("Authorization", ApiKeyAuth) const url = `${baseUrl.replace(/\/+$/, '')}/ws/listings/detail${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(getApiWsListingsDetailResponse, await res.json()) };