import {z} from 'zod' export type GetApiApiResourceLwm2mArgs = {sortOrder: 'ASC' | 'DESC', sortProperty: 'id' | 'name', objectIds: Array}; export type GetApiApiResourceLwm2mOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const lwM2mResourceObserve = z.object({id: z.number().int().optional(), name: z.string().optional(), observe: z.boolean().optional(), attribute: z.boolean().optional(), telemetry: z.boolean().optional(), keyName: z.string().optional()}); export const lwM2mInstance = z.object({id: z.number().int().optional(), resources: z.array(lwM2mResourceObserve).optional()}); export const lwM2mObject = z.object({id: z.number().int().optional(), keyId: z.string().optional(), name: z.string().optional(), multiple: z.boolean().optional(), mandatory: z.boolean().optional(), instances: z.array(lwM2mInstance).optional()}); export const getApiApiResourceLwm2mResponse = z.array(lwM2mObject); 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 }; /** * Get LwM2M Objects (getLwm2mListObjects) * * GET /api/resource/lwm2m */ export const getApiApiResourceLwm2m = async (args: GetApiApiResourceLwm2mArgs, options?: GetApiApiResourceLwm2mOptions) => { const {baseUrl = "https://demo.thingsboard.io", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.sortOrder != null) query.append("sortOrder", String(args.sortOrder)) if (args.sortProperty != null) query.append("sortProperty", String(args.sortProperty)) for (const item of args.objectIds ?? []) query.append("objectIds", String(item)) const url = `${baseUrl.replace(/\/+$/, '')}/api/resource/lwm2m${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(getApiApiResourceLwm2mResponse, await res.json()) };