import {z} from 'zod' export type CreateProductRequest = {code: string, name: string, price?: number | undefined, categories?: Array | undefined, attributes?: {[key: string]: unknown} | undefined}; export type CreateApiV1ProductsArgs = {_with_approval?: boolean | undefined, body: CreateProductRequest}; export type CreateApiV1ProductsOptions = {baseUrl: string, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const product = z.object({_id: z.string().optional(), deleted: z.boolean().optional(), created_at: z.string().optional(), created_by: z.string().optional(), updated_at: z.string().optional(), updated_by: z.string().optional(), deleted_at: z.string().nullable().optional(), deleted_by: z.string().nullable().optional(), code: z.string().optional(), name: z.string().optional(), price: z.number().optional(), categories: z.array(z.string()).optional(), attributes: z.record(z.string(), z.unknown()).optional()}); export const productResponse = z.object({data: product.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 a new product * * POST /v1/products */ export const createApiV1Products = async (args: CreateApiV1ProductsArgs, options: CreateApiV1ProductsOptions) => { const {baseUrl, fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args._with_approval != null) query.append("_with_approval", String(args._with_approval)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/products${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(productResponse, await res.json()) };