import {z} from 'zod' export type GetApiV1RegistrationDeathArgs = {forenames: string, surname: string, date: string}; export type GetApiV1RegistrationDeathOptions = {baseUrl?: string | undefined, bearerToken?: string | undefined, fetch?: typeof fetch | undefined}; export const v1Death = z.object({id: z.number().int(), date: z.string(), deceased: z.object({forenames: z.string(), surname: z.string(), dateOfBirth: z.string().optional(), dateOfDeath: z.string(), sex: z.enum(["Male", "Female", "Indeterminate"]), birthplace: z.string().optional(), deathplace: z.string().optional(), occupation: z.string().optional(), address: z.string().optional(), retired: z.boolean().optional(), maidenSurname: z.string().optional()}), status: z.object({blocked: z.boolean()})}); export const v1Deaths = z.array(v1Death); 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 }; /** * Search for death records * * GET /v1/registration/death */ export const getApiV1RegistrationDeath = async (args: GetApiV1RegistrationDeathArgs, options?: GetApiV1RegistrationDeathOptions) => { const {baseUrl = "https://api.lev.homeoffice.gov.uk", fetch: fetchFn = fetch, bearerToken} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.forenames != null) query.append("forenames", String(args.forenames)) if (args.surname != null) query.append("surname", String(args.surname)) if (args.date != null) query.append("date", String(args.date)) if (bearerToken !== undefined) headers.set('authorization', `Bearer ${bearerToken}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/registration/death${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(v1Deaths, await res.json()) };