UNPKG

homebridge-poolcontroller-clocklear

Version:

A (semi) private Homebridge plugin for my custom Pool Controller app

67 lines 2.51 kB
export class PoolControllerClient { cacheTTLSecs; baseUrl; apiKey; cache = null; cacheTimestamp = null; cachePromise = null; constructor(baseUrl, apiKey, cacheTTLSecs = 60) { this.cacheTTLSecs = cacheTTLSecs; this.baseUrl = baseUrl; this.apiKey = apiKey; } async request(endpoint, options) { const url = `${this.baseUrl}${endpoint}`; const config = { ...options, headers: { 'Content-Type': 'application/json', 'X-API-KEY': `${this.apiKey}`, ...(options && options.headers), }, }; const response = await fetch(url, config); if (!response.ok) { throw new Error(`Error: ${response.statusText}`); } return response.json(); } isCacheValid() { return this.cache !== null && this.cacheTimestamp !== null && (Date.now() - this.cacheTimestamp) < this.cacheTTLSecs * 1000; } // Get all relays and their states async getRelays() { if (this.isCacheValid()) { return this.cache; } if (this.cachePromise) { // If there's an ongoing request to update the cache, wait for it to complete return this.cachePromise; } // Create a new promise to update the cache this.cachePromise = (async () => { const relayStatesResponse = await this.request('/relays'); this.cache = relayStatesResponse.relayStates; this.cacheTimestamp = Date.now(); this.cachePromise = null; // Reset the promise after completing the request return this.cache; })(); return this.cachePromise; } // Toggle the state of a relay. The new state is returned. async toggleRelay(relayId) { const relayStatesResponse = await this.request(`/relays/${relayId}/toggle`, { method: 'POST', }); this.cache = relayStatesResponse.relayStates; this.cacheTimestamp = Date.now(); this.cachePromise = null; // Clear any ongoing cache update promise since we have fresh data now return this.cache.find((relayState) => relayState.relay === relayId); } // Get the state of a single relay async getRelayState(relayId) { const relays = await this.getRelays(); return relays.find((relayState) => relayState.relay === relayId); } } //# sourceMappingURL=poolControllerClient.js.map