import {z} from 'zod' export type CreateApiIso20022MessagePathArgs = {messagePath: 'pacs.008' | 'pacs.002' | 'pacs.028' | 'acmt.023' | 'acmt.024' | 'camt.054' | 'camt.056' | 'camt.029' | 'admi.002' | 'admi.004', body: BodyInit}; export type CreateApiIso20022MessagePathOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const technicalAckDto = z.object({uetr: z.string().optional(), messageType: z.enum(["pacs.008", "pacs.002", "pacs.028", "acmt.023", "acmt.024", "camt.054", "camt.056", "camt.029", "admi.002", "admi.004"]), msgId: z.string().min(24).max(35).optional(), receivedAt: z.string(), status: z.enum(["RECEIVED", "REJECTED"]), ackCode: 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 }; /** * Submit ISO 20022 message * * POST /iso20022/{messagePath} */ export const createApiIso20022MessagePath = async (args: CreateApiIso20022MessagePathArgs, options?: CreateApiIso20022MessagePathOptions) => { const {baseUrl = "http://localhost:8080", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/xml") headers.set('accept', "application/json") if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/iso20022/${encodeURIComponent(String(args.messagePath))}${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: args.body}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(technicalAckDto, await res.json()) };