import {z} from 'zod' export type GetApiProfileArgs = {search?: string | undefined, ordering?: string | undefined, limit?: number | undefined, offset?: number | undefined}; export type GetApiProfileOptions = {baseUrl?: string | undefined, BearerAdmin?: string | undefined, fetch?: typeof fetch | undefined}; export const teamProfile = z.object({name: z.string().min(1).max(100), public_id: z.string().optional(), url: z.string().optional(), avatar: z.string().min(1).nullable().optional()}); export const profileList = z.object({url: z.string().optional(), public_id: z.string().optional(), name: z.string().min(1).optional(), gender: z.enum(["M", "F", "X"]).optional(), teams: z.array(teamProfile).optional(), reference: z.string().max(255).optional(), avatar: z.string().min(1).nullable().optional()}); export const getApiProfileResponse = z.object({count: z.number().int(), next: z.string().nullable().optional(), previous: z.string().nullable().optional(), results: z.array(profileList)}); 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 }; /** * List Profiles * * GET /profile/ * * Also accepts auth: BearerProfile */ export const getApiProfile = async (args: GetApiProfileArgs, options?: GetApiProfileOptions) => { const {baseUrl = "https://api.wefitter.com/api/v1", fetch: fetchFn = fetch, BearerAdmin} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.search != null) query.append("search", String(args.search)) if (args.ordering != null) query.append("ordering", String(args.ordering)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.offset != null) query.append("offset", String(args.offset)) if (BearerAdmin !== undefined) headers.set("Authorization", BearerAdmin) const url = `${baseUrl.replace(/\/+$/, '')}/profile/${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(getApiProfileResponse, await res.json()) };