Newer
Older
smart-home-server / webclient-vue / src / api / client.js
@Eugene Sukhodolskiy Eugene Sukhodolskiy 8 hours ago 1 KB Scaffold Vue web client
import { requestHttp } from "./http";

function makeError(type, message, extra = {}) {
  return {
    type,
    message,
    ...extra,
  };
}

export async function apiRequest(method, path, body, options) {
  try {
    const { response, data, meta } = await requestHttp(method, path, body, options);

    if (!response.ok) {
      return {
        ok: false,
        error: makeError("http_error", `HTTP ${response.status}`, {
          statusCode: response.status,
          raw: data,
        }),
        meta,
      };
    }

    if (data && typeof data === "object" && (data.status === false || data.status === "error")) {
      return {
        ok: false,
        error: makeError("api_error", data.msg || data.message || "API error", {
          errorAlias: data.error_alias,
          failedFields: data.failed_fields || [],
          raw: data,
        }),
        meta,
      };
    }

    return {
      ok: true,
      data,
      meta,
    };
  } catch (error) {
    const isAbort = error?.name === "AbortError";
    return {
      ok: false,
      error: makeError(isAbort ? "timeout" : "network_error", error?.message || "Network error", {
        details: error,
      }),
      meta: {
        url: path,
        method,
        statusCode: 0,
        headers: null,
      },
    };
  }
}

export function apiGet(path, options) {
  return apiRequest("GET", path, null, options);
}

export function apiPost(path, body, options) {
  return apiRequest("POST", path, body, options);
}