@vertical-insure/web-components
Version: 
Vertical Insure Web Components using Lit and Open Web Standards
63 lines (62 loc) • 2.11 kB
JavaScript
import axios from "axios";
import { ControllerStatus, apiHost } from "./utils.js";
class ProductController {
  constructor(host, onChange) {
    this.status = ControllerStatus.PENDING;
    (this.host = host).addController(this);
    this.onChange = onChange;
  }
  async hostUpdated() {
    if (this.host.clientId !== void 0 && this.host.product !== void 0 && this.value === void 0 && this.status !== ControllerStatus.ERROR) {
      await this.loadProduct();
    }
  }
  async loadProduct() {
    var _a;
    this.status = ControllerStatus.PENDING;
    try {
      let endpoint = `${apiHost}/v1/products/${this.host.product}`;
      if (this.host.offerId) {
        endpoint += `?offer_id=${encodeURIComponent(this.host.offerId)}`;
      }
      const response = await axios.get(endpoint, {
        headers: {
          "Content-Type": "application/json",
          "x-api-client-id": this.host.clientId,
          "x-api-source": "Web Component"
        }
      });
      this.status = ControllerStatus.COMPLETE;
      this.value = response.data;
      this.onChange();
      this.host.requestUpdate();
    } catch (e) {
      this.status = ControllerStatus.ERROR;
      const responseError = e;
      const data = (_a = responseError.response) == null ? void 0 : _a.data;
      if (data && !data._embedded) {
        this.error = new Error(data.message, { cause: data.error });
      }
      if (this.host.debug) {
        console.debug("Failed to retrieve product", data == null ? void 0 : data._embedded);
      }
    }
    this.host.requestUpdate();
  }
  render(renderer) {
    var _a, _b, _c;
    switch (this.status) {
      case ControllerStatus.PENDING:
        return (_a = renderer.pending) == null ? void 0 : _a.call(renderer);
      case ControllerStatus.COMPLETE:
        return (_b = renderer.complete) == null ? void 0 : _b.call(renderer, this.value);
      case ControllerStatus.ERROR:
        return (_c = renderer.error) == null ? void 0 : _c.call(renderer, this.error);
      default:
        throw new Error(`Unexpected status: ${this.status}`);
    }
  }
}
export {
  ProductController
};