import {z} from 'zod' export type GetApiOrdersArgs = {startDate?: string | undefined, endDate?: string | undefined, isoCode?: string | undefined}; export type GetApiOrdersOptions = {baseUrl?: string | undefined, AuthHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const cost = z.object({type: z.enum(["credit", "lite"]).optional(), value: z.number().optional()}); export const orderDetails = z.object({orderId: z.number().int().optional(), orderDate: z.string().optional(), customerReference: z.string().optional(), status: z.enum(["Success", "Pending", "Failed"]).optional(), failureReason: z.string().optional(), cost: cost.optional(), user: z.string().optional(), productDetails: z.object({productName: z.string().optional(), productId: z.string().optional(), productCategory: z.string().optional()}).optional(), companyDetails: z.object({companyName: z.string().optional(), companyNumber: z.string().optional(), kyckrID: z.string().optional()}).optional(), links: z.object({data: z.string().optional(), document: z.string().optional()}).optional()}); export const getApiOrdersResponse = z.object({orderId: z.string().optional(), correlationId: z.string().optional(), customerReference: z.string().optional(), timeStamp: z.string().optional(), details: z.string().optional(), cost: cost.optional(), links: z.object({self: z.string().optional()}).optional(), data: z.array(orderDetails).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 }; /** * Get List of Orders * * GET /orders */ export const getApiOrders = async (args: GetApiOrdersArgs, options?: GetApiOrdersOptions) => { const {baseUrl = "https://api.kyckr.com/v2", fetch: fetchFn = fetch, AuthHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.startDate != null) query.append("startDate", String(args.startDate)) if (args.endDate != null) query.append("endDate", String(args.endDate)) if (args.isoCode != null) query.append("isoCode", String(args.isoCode)) if (AuthHeader !== undefined) headers.set('authorization', `Bearer ${AuthHeader}`) const url = `${baseUrl.replace(/\/+$/, '')}/orders${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(getApiOrdersResponse, await res.json()) };