import {z} from 'zod' export type TicketType = 'event' | 'general'; export type EventId = string; export type Date = string; export type Email = string; export type Phone = string; export type BuyMuseumTicketsRequest = {ticketType: TicketType, eventId?: EventId | undefined, ticketDate: Date, email: Email, phone?: Phone | undefined}; export type CreateApiTicketsArgs = {body: BuyMuseumTicketsRequest}; export type CreateApiTicketsOptions = {baseUrl?: string | undefined, MuseumPlaceholderAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const ticketMessage = z.string(); export const eventName = z.string(); export const ticketId = z.string(); export const ticketType = z.enum(["event", "general"]); export const date = z.string(); export const ticketConfirmation = z.string(); export const buyMuseumTicketsResponse = z.object({message: ticketMessage, eventName: eventName.optional(), ticketId: ticketId, ticketType: ticketType, ticketDate: date, confirmationCode: ticketConfirmation}); 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 }; /** * Buy museum tickets * * POST /tickets */ export const createApiTickets = async (args: CreateApiTicketsArgs, options?: CreateApiTicketsOptions) => { const {baseUrl = "https://api.fake-museum-example.com/v1", fetch: fetchFn = fetch, MuseumPlaceholderAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (MuseumPlaceholderAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${MuseumPlaceholderAuth.username}:${MuseumPlaceholderAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/tickets${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(buyMuseumTicketsResponse, await res.json()) };