import {z} from 'zod' export type WidgetSettingResource = {widgetSettingId?: number | undefined, widgetId?: number | undefined, i?: string | undefined, x?: number | undefined, y?: number | undefined, w?: number | undefined, h?: number | undefined, minW?: number | undefined, minH?: number | undefined}; export type UserWidgetsResource = {userId?: number | undefined, widgetSettings?: Array | undefined}; export type CreateApiWidgetSettingArgs = {body: UserWidgetsResource}; export type CreateApiWidgetSettingOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const widgetSettingResource = z.object({widgetSettingId: z.number().int().optional(), widgetId: z.number().int().optional(), i: z.string().optional(), x: z.number().int().optional(), y: z.number().int().optional(), w: z.number().int().optional(), h: z.number().int().optional(), minW: z.number().int().optional(), minH: z.number().int().optional()}); export const userWidgetsResource = z.object({userId: z.number().int().optional(), widgetSettings: z.array(widgetSettingResource).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 }; /** * Creates a new widget setting related to user * * POST /widget_setting */ export const createApiWidgetSetting = async (args: CreateApiWidgetSettingArgs, options?: CreateApiWidgetSettingOptions) => { const {baseUrl = "http://localhost:9090", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/widget_setting${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(userWidgetsResource, await res.json()) };