UNPKG

@devmehq/open-graph-extractor

Version:

Fast, lightweight Open Graph, Twitter Card, and structured data extractor for Node.js with caching and validation

93 lines (92 loc) 2.8 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createCache = createCache; const tiny_lru_1 = require("tiny-lru"); /** * Default key generator - creates cache key from URL */ function defaultKeyGenerator(url) { try { const urlObj = new URL(url); urlObj.hash = ""; const params = new URLSearchParams(urlObj.search); const sortedParams = new URLSearchParams([...params.entries()].sort()); urlObj.search = sortedParams.toString(); return `og:${urlObj.toString()}`; } catch { return `og:${url}`; } } /** * Create a cache manager with specified options */ function createCacheManager(options) { const enabled = options?.enabled ?? false; const keyGenerator = options?.keyGenerator ?? defaultKeyGenerator; if (!enabled) { return { get: async () => null, set: async () => { }, delete: async () => { }, clear: async () => { }, has: async () => false, getStats: () => null, }; } if (options?.customStorage) { return { async get(url) { const key = keyGenerator(url); return await options.customStorage?.get(key); }, async set(url, value, customTtl) { const key = keyGenerator(url); await options.customStorage?.set(key, value, customTtl); }, async delete(url) { const key = keyGenerator(url); await options.customStorage?.delete(key); }, async clear() { await options.customStorage?.clear(); }, async has(url) { const key = keyGenerator(url); return await options.customStorage?.has(key); }, getStats: () => null, }; } const ttl = (options?.ttl ?? 3600) * 1000; const maxSize = options?.maxSize ?? 1000; const cache = (0, tiny_lru_1.lru)(maxSize, ttl); return { async get(url) { const key = keyGenerator(url); return cache.get(key) || null; }, async set(url, value, _customTtl) { const key = keyGenerator(url); cache.set(key, value); }, async delete(url) { const key = keyGenerator(url); cache.delete(key); }, async clear() { cache.clear(); }, async has(url) { const key = keyGenerator(url); return cache.has(key); }, getStats: () => null, }; } /** * Create a cache manager with default settings */ function createCache(options) { return createCacheManager(options); }