import {z} from 'zod' export type CreateApiV3ProductvariantArgs = {id: number, echo: boolean, body: {name: string, cost?: number | undefined, price?: number | undefined, primaryId?: number | undefined, properties?: Record | undefined}}; export type CreateApiV3ProductvariantOptions = {baseUrl?: string | undefined, sec0?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const createApiV3ProductvariantResponse = z.object({id: z.number().int().optional(), dateCreated: z.string().optional(), dateModified: z.string().optional(), name: z.string().optional(), productId: z.number().int().optional(), primaryId: z.string().optional(), price: z.string().optional(), cost: z.string().optional(), notifyOnLowStock: z.boolean().optional(), hideOnNoStock: z.boolean().optional(), tags: z.array(z.object({})).optional(), isActive: z.boolean().optional(), isDeleted: z.boolean().optional(), onHand: z.number().int().optional(), properties: z.object({}).optional(), productProperties: z.object({}).optional()}); 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 }; /** * Create Variant * * POST /v3/productvariant */ export const createApiV3Productvariant = async (args: CreateApiV3ProductvariantArgs, options?: CreateApiV3ProductvariantOptions) => { const {baseUrl = "https://sandbox.api.mxmerchant.com/checkout", fetch: fetchFn = fetch, sec0} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (sec0 !== undefined) headers.set('authorization', `Basic ${btoa(`${sec0.username}:${sec0.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/v3/productvariant${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(createApiV3ProductvariantResponse, await res.json()) };