import {z} from 'zod' export type GetApiV2PublishersCouponsArgs = {pageToken?: string | undefined, campaign_id?: string | undefined}; export type GetApiV2PublishersCouponsOptions = {baseUrl?: string | undefined, APIKey?: string | undefined, fetch?: typeof fetch | undefined}; export const publisherCouponCodeData = z.object({coupons: z.array(z.object({id: z.string().optional(), code: z.string().optional(), description: z.string().optional(), status: z.enum(["active", "pending", "expired"]).optional(), type: z.enum(["generic", "exclusive", "one_time"]).optional(), campaign_name: z.string().optional(), campaign_id: z.number().optional(), start: z.string().optional(), end: z.string().optional(), created: z.string().optional()})).optional(), pageToken: z.string().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 }; /** * Fetch All Coupons * * GET /v2/publishers/coupons */ export const getApiV2PublishersCoupons = async (args: GetApiV2PublishersCouponsArgs, options?: GetApiV2PublishersCouponsOptions) => { const {baseUrl = "https://api.trackier.com", fetch: fetchFn = fetch, APIKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.pageToken != null) query.append("pageToken", String(args.pageToken)) if (args.campaign_id != null) query.append("campaign_id", String(args.campaign_id)) if (APIKey !== undefined) headers.set("X-Api-Key", APIKey) const url = `${baseUrl.replace(/\/+$/, '')}/v2/publishers/coupons${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(publisherCouponCodeData, await res.json()) };