import {z} from 'zod' export type GetApiV2RelatedItemsOptions = {baseUrl: string, oauth2?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiV2RelatedItemsResponse = z.array(z.object({id: z.number().int().optional(), type: z.enum(["VALUE", "ENTITY"]).optional(), entity: z.object({}).optional(), entityId: z.number().int().optional(), entityType: z.enum(["ORGANIZATION", "DOCUMENT", "LOCATION", "NODE", "CHECKLIST", "KB_DOCUMENT", "END_USER", "SOFTWARE_LICENSE"]).optional(), relEntity: z.object({}).optional(), relEntityId: z.number().int().optional(), relEntityType: z.enum(["ORGANIZATION", "DOCUMENT", "LOCATION", "NODE", "ATTACHMENT", "TECHNICIAN", "CREDENTIAL", "CHECKLIST", "END_USER", "CONTACT", "KB_DOCUMENT", "SOFTWARE_LICENSE", "SECURE"]).optional(), value: z.object({}).optional(), createTime: z.number().optional(), updateTime: z.number().optional(), createdByAppUserId: z.number().int().optional(), updatedByAppUserId: z.number().int().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 }; /** * List all related items * * GET /v2/related-items * * Also accepts auth: sessionKey */ export const getApiV2RelatedItems = async (options: GetApiV2RelatedItemsOptions) => { const {baseUrl, fetch: fetchFn = fetch, oauth2} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (oauth2 !== undefined) headers.set('authorization', `Bearer ${oauth2}`) const url = `${baseUrl.replace(/\/+$/, '')}/v2/related-items${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(getApiV2RelatedItemsResponse, await res.json()) };