All files / src/live ContactStoreElement.ts

80.88% Statements 55/68
81.81% Branches 9/11
75% Functions 3/4
80.88% Lines 55/68

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 6992x 92x 92x 92x 92x 92x 15x 15x 15x 15x 15x 15x 15x 15x 92x 92x 16x 16x 16x 30x 16x 16x 16x 14x 14x 13x 13x 1x 1x 1x 1x 14x     16x 16x 16x 16x   16x 92x 92x                     92x 92x 1x 1x 1x 1x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x  
import { PropertyValues } from 'lit';
import { property } from 'lit/decorators.js';
import { Contact, Group } from '../interfaces';
import { EndpointMonitorElement } from '../store/EndpointMonitorElement';
 
export class ContactStoreElement extends EndpointMonitorElement {
  @property({ type: String })
  contact: string;
 
  @property({ type: Object, attribute: false })
  data: Contact;
 
  @property({ type: String })
  endpoint = '/api/v2/contacts.json?uuid=';
 
  prepareData(data: any) {
    if (data && data.length > 0) {
      data = data[0];
      data.groups.forEach((group: Group) => {
        group.is_dynamic = this.store.isDynamicGroup(group.uuid);
      });
 
      data.groups.sort((a: Group, b: Group) => {
        if (!a.is_dynamic || !b.is_dynamic) {
          if (a.is_dynamic) {
            return -1;
          }
 
          if (b.is_dynamic) {
            return 1;
          }
        }

        return a.name.localeCompare(b.name);
      });
 
      return data;
    }
    return null;
  }
 
  public postChanges(payload: any) {
    // clear our cache so we don't have any races
    this.store.removeFromCache(`${this.endpoint}${this.contact}`);
    return this.store
      .postJSON(`${this.endpoint}${this.contact}`, payload)
      .then((response) => {
        this.setContact(response.json);
      });
  }

  public setContact(contact: any) {
    // make sure contact data is properly prepped
    this.data = this.prepareData([contact]);
    this.store.updateCache(`${this.endpoint}${this.contact}`, this.data);
  }
 
  public willUpdate(changed: PropertyValues): void {
    super.willUpdate(changed);
    if (changed.has('contact') || changed.has('endpoint')) {
      if (this.contact) {
        this.url = `${this.endpoint}${this.contact}`;
      } else {
        this.url = null;
      }
    }
  }
}