import {z} from 'zod' export type IRole = {id: string, orgKey: string, name: string, description: string, creationdate: number, permissions: Array}; export type CreateApiRolesArgs = {orgkey?: string | undefined, body: IRole}; export type CreateApiRolesOptions = {baseUrl?: string | undefined, cognitoJwtAuthorizer?: string | undefined, fetch?: typeof fetch | undefined}; export const iRole = z.object({id: z.string(), orgKey: z.string(), name: z.string(), description: z.string(), creationdate: z.number(), permissions: z.array(z.string())}); export const createApiRolesResponse = z.object({data: iRole.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 }; /** * addRole * * POST /roles/ */ export const createApiRoles = async (args: CreateApiRolesArgs, options?: CreateApiRolesOptions) => { const {baseUrl = "https://api-hub.extensiv.com", fetch: fetchFn = fetch, cognitoJwtAuthorizer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.orgkey != null) query.append("orgkey", String(args.orgkey)) if (cognitoJwtAuthorizer !== undefined) headers.set('authorization', `Bearer ${cognitoJwtAuthorizer}`) const url = `${baseUrl.replace(/\/+$/, '')}/roles/${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(createApiRolesResponse, await res.json()) };