UNPKG

@mrgalaxy/tjme

Version:
65 lines 2.36 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getRandomColor = exports.getColors = exports.refresh = exports.colors = exports.isColorAPIData = void 0; const tslib_1 = require("tslib"); const node_fetch_1 = tslib_1.__importDefault(require("node-fetch")); const randomcolor_1 = tslib_1.__importDefault(require("randomcolor")); function isColorAPIData(obj) { return (obj != null && obj.name != null && typeof obj.name.value === "string" && typeof obj.name.closest_named_hex === "string" && typeof obj.name.exact_match_name === "boolean" && typeof obj.name.distance === "number" && obj.hex != null && typeof obj.hex.value === "string" && typeof obj.hex.clean === "string"); } exports.isColorAPIData = isColorAPIData; exports.colors = []; async function refresh() { const result = await getColors(20); if (!Array.isArray(result)) return []; exports.colors.splice(0, exports.colors.length); exports.colors.push(...result); return exports.colors; } exports.refresh = refresh; async function getColors(count) { const randhex = Array.from(new Array(count), () => (0, randomcolor_1.default)({ luminosity: "dark", format: "hex" }).substring(1)); const result = []; for (const hex of randhex) { const resp = await (0, node_fetch_1.default)(`https://www.thecolorapi.com/id?hex=${hex}`); if (!resp.ok) { throw new Error("Failed to fetch."); } const data = await resp.json(); if (!isColorAPIData(data)) { throw new Error("Invalid response."); } result.push(data); // sleep a bit since this is a free API await new Promise((ok) => setTimeout(ok, 500)); } return result; } exports.getColors = getColors; function getRandomColor() { return exports.colors[Math.floor(Math.random() * exports.colors.length)]; } exports.getRandomColor = getRandomColor; async function update() { try { await refresh(); console.log("[%s] Colors Updated.", new Date().toISOString()); } catch (e) { console.error("Problem fetching colors."); console.error(e.stack || e); } } // grab immediately and every 24 hours update(); setInterval(update, 1000 * 60 * 60 * 24); //# sourceMappingURL=colors.js.map