import {z} from 'zod' export type GetApiSavingsGoalsGoalIdArgs = {goalId: string}; export type GetApiSavingsGoalsGoalIdOptions = {baseUrl?: string | undefined, Bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const savingsGoals = z.object({id: z.string(), name: z.string(), amount: z.object({value: z.number().int().gt(0), majorUnits: z.number().int().optional(), minorUnits: z.number().int().optional(), currency: z.string()}), targetDate: z.string().optional(), dateCreated: z.string(), imageUrl: z.string().optional(), notes: z.string().optional(), progressPercentage: z.number().optional(), progressAmount: z.object({value: z.number().int().optional(), majorUnits: z.number().int().optional(), minorUnits: z.number().int().optional(), currency: z.string().optional()}).optional(), accounts: z.array(z.object({id: z.string()}))}); export const links = z.object({next: z.string().optional(), prev: z.string().optional(), self: z.string()}); export const getApiSavingsGoalsGoalIdResponse = z.object({data: savingsGoals.optional(), links: links.optional(), meta: z.object({}).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 }; /** * Retrieve a single savings goal * * GET /savings-goals/{goalId} */ export const getApiSavingsGoalsGoalId = async (args: GetApiSavingsGoalsGoalIdArgs, options?: GetApiSavingsGoalsGoalIdOptions) => { const {baseUrl = "https://api.moneyhub.co.uk/v2.0", fetch: fetchFn = fetch, Bearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (Bearer !== undefined) headers.set("Authorization", Bearer) const url = `${baseUrl.replace(/\/+$/, '')}/savings-goals/${encodeURIComponent(String(args.goalId))}${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(getApiSavingsGoalsGoalIdResponse, await res.json()) };