import { MessageBase } from 'home-assistant-js-websocket'; import { ZodSchema } from 'zod'; import { localize } from '../localize/localize'; import { AdvancedCameraCardError } from '../types'; import { HomeAssistant } from './types'; /** * Make a HomeAssistant websocket request. May throw. * @param hass The HomeAssistant object to send the request with. * @param schema The expected Zod schema of the response. * @param request The request to make. * @returns The parsed valid response or null on malformed. */ export async function homeAssistantWSRequest( hass: HomeAssistant, schema: ZodSchema, request: MessageBase, passthrough = false, ): Promise { let response: unknown; try { response = await hass.callWS(request); } catch (e) { throw new AdvancedCameraCardError(localize('error.failed_response'), { request: request, response: e, }); } if (!response) { throw new AdvancedCameraCardError(localize('error.empty_response'), { request: request, }); } try { // Some endpoints in Home Assistant pass JSON directly though, these end up // wrapped in a string and must be unwrapped first. return schema.parse(passthrough ? JSON.parse(response as string) : response); // eslint-disable-next-line @typescript-eslint/no-unused-vars } catch (_e) { throw new AdvancedCameraCardError(localize('error.invalid_response'), { request: request, response: response, }); } }