import {z} from 'zod' export type ExternalAPIContractsRequestsV1AddTimeOffRequest = {user: string | null, title: string | null, start: string, finish: string}; export type CreateApiApiV1TimeoffsArgs = {body: Array}; export type CreateApiApiV1TimeoffsOptions = {baseUrl: string, TeamhoodAPIKey?: string | undefined, fetch?: typeof fetch | undefined}; export const externalAPIContractsResponsesV1EntitiesTimeOff = z.object({id: z.string(), title: z.string().nullable(), start: z.string(), finish: z.string(), isAllCompany: z.boolean(), userIds: z.array(z.string()).nullable()}); export const externalAPIContractsResponsesV1AddTimeOffsResponse = z.object({timeOffs: z.array(externalAPIContractsResponsesV1EntitiesTimeOff).nullable()}); 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 }; /** * Add Time Offs * * POST /api/v1/timeoffs */ export const createApiApiV1Timeoffs = async (args: CreateApiApiV1TimeoffsArgs, options: CreateApiApiV1TimeoffsOptions) => { const {baseUrl, fetch: fetchFn = fetch, TeamhoodAPIKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (TeamhoodAPIKey !== undefined) headers.set("X-ApiKey", TeamhoodAPIKey) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/timeoffs${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(externalAPIContractsResponsesV1AddTimeOffsResponse, await res.json()) };