import {z} from 'zod' export type GetApiV1RewardsRewardIdOptions = {baseUrl?: string | undefined, XAppId?: string | undefined, XAppToken?: string | undefined, fetch?: typeof fetch | undefined}; export const rewardTypeCampaign = z.object({campaign: z.object({id: z.string(), balance: z.number().int().optional(), type: z.enum(["DISCOUNT_COUPONS", "GIFT_VOUCHERS", "LOYALTY_PROGRAM"])})}); export const rewardTypeCoin = z.object({coin: z.object({exchange_ratio: z.number(), points_ratio: z.number().int().optional()})}); export const rewardTypeMaterial = z.object({product: z.object({id: z.string(), sku_id: z.string().nullable().optional()})}); export const rewardType = z.union([rewardTypeCampaign, rewardTypeCoin, rewardTypeMaterial]); export const reward = z.object({id: z.string(), name: z.string(), stock: z.number().int().nullable(), redeemed: z.number().int().nullable(), attributes: z.object({image_url: z.string().optional(), description: z.string().optional()}).optional(), metadata: z.object({}), type: z.enum(["CAMPAIGN", "COIN", "MATERIAL"]), parameters: rewardType.optional(), created_at: z.string(), updated_at: z.string().nullable(), object: z.literal("reward")}); 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 Reward * * GET /v1/rewards/{rewardId} * * Also accepts auth: X-Voucherify-OAuth */ export const getApiV1RewardsRewardId = async (options?: GetApiV1RewardsRewardIdOptions) => { const {baseUrl = "https://api.voucherify.io", fetch: fetchFn = fetch, XAppId, XAppToken} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (XAppId !== undefined) headers.set("X-App-Id", XAppId) if (XAppToken !== undefined) headers.set("X-App-Token", XAppToken) const url = `${baseUrl.replace(/\/+$/, '')}/v1/rewards/${encodeURIComponent(String(args.rewardId))}${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(reward, await res.json()) };