import {z} from 'zod' export type GetApiV1VerificationUpiArgs = {vpa: string, name?: string | undefined}; export type GetApiV1VerificationUpiOptions = {baseUrl: string, Oauth2ClientCredentials?: string | undefined, fetch?: typeof fetch | undefined}; export const vPASUCCESS = z.object({account_exists: z.boolean(), name_at_bank: z.string().optional()}); export const rESPONSEUPIVERIFICATIONSUCCESSFUL = z.object({code: z.number().int(), timestamp: z.number().int(), transaction_id: z.string(), data: vPASUCCESS}); export const vPAFAIL = z.object({account_exists: z.boolean()}); export const rESPONSEUPIVERIFICATIONFAILURE = z.object({code: z.number().int(), timestamp: z.number().int(), transaction_id: z.string(), data: vPAFAIL}); export const getApiV1VerificationUpiResponse = z.union([rESPONSEUPIVERIFICATIONSUCCESSFUL, rESPONSEUPIVERIFICATIONFAILURE]); 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 }; /** * Upi Verification * * GET /v1/verification/upi */ export const getApiV1VerificationUpi = async (args: GetApiV1VerificationUpiArgs, options: GetApiV1VerificationUpiOptions) => { const {baseUrl, fetch: fetchFn = fetch, Oauth2ClientCredentials} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.vpa != null) query.append("vpa", String(args.vpa)) if (args.name != null) query.append("name", String(args.name)) if (Oauth2ClientCredentials !== undefined) headers.set('authorization', `Bearer ${Oauth2ClientCredentials}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/verification/upi${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(getApiV1VerificationUpiResponse, await res.json()) };