@elshaer/homebridge-lg-thinq
Version:
A Homebridge plugin for controlling/monitoring LG ThinQ device via LG ThinQ platform.
87 lines • 3.02 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const NodePersist = __importStar(require("node-persist"));
class Persist {
constructor(dir) {
this.persist = NodePersist.create({
dir,
});
}
async init() {
return await this.persist.init();
}
async getItem(key) {
return await this.persist.getItem(key);
}
async setItem(key, value) {
return await this.persist.setItem(key, value);
}
async cacheForever(key, callable) {
let value = await this.getItem(key);
if (!value) {
value = await callable();
await this.setItem(key, value);
}
return value;
}
async cache(key, ttl, callable) {
let value = await this.getWithExpiry(key);
if (!value) {
value = await callable();
await this.setWithExpiry(key, value, ttl);
}
return value;
}
async setWithExpiry(key, value, ttl) {
const now = new Date();
// `item` is an object which contains the original value
// as well as the time when it's supposed to expire
const item = {
value: value,
expiry: now.getTime() + ttl,
};
await this.persist.setItem(key, JSON.stringify(item));
}
async getWithExpiry(key) {
const itemStr = await this.persist.getItem(key);
// if the item doesn't exist, return null
if (!itemStr) {
return null;
}
const item = JSON.parse(itemStr);
const now = new Date();
// compare the expiry time of the item with the current time
if (now.getTime() > item.expiry) {
// If the item is expired, delete the item from storage
// and return null
await this.persist.removeItem(key);
return null;
}
return item.value;
}
}
exports.default = Persist;
//# sourceMappingURL=Persist.js.map