UNPKG

cache-api-local

Version:

A lib to use for caching the api res so your load to serve minimize. Plus it has revalidating feature 🔥🔥

3 lines (2 loc) • 2.26 kB
"use strict";var e=require("fs"),t=require("path");function r(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var a=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,a.get?a:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var a=r(e),n=r(t);module.exports=class{constructor(e,t,r){this.basePath=e;const a=function(){const e=Error.prepareStackTrace;let t;try{const e=new Error;Error.prepareStackTrace=(e,t)=>t;const r=e.stack;r?.length>2&&(t=r[2].getFileName()??void 0)}catch(e){console.error("Error determining caller directory:",e)}finally{Error.prepareStackTrace=e}if(t?.startsWith("file:///")){let e=new URL(t).pathname;return"win32"===process.platform&&e.startsWith("/")&&(e=e.slice(1)),n.dirname(e)}return t?n.dirname(t):process.cwd()}();this.actualBaseCachePath=n.resolve(a,t),this.maxAge=r}sanitizeFilename(e){return e.replace(/[\/*?:"<>|\\]/g,"_").replace(/\s+/g,"_").replace(/^_+/,"")}readJSONSafe(e){try{const t=a.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return null}}writeJSON(e,t){a.writeFileSync(e,JSON.stringify(t,null,2),"utf-8")}getFilePaths(e,t){const r=this.sanitizeFilename(decodeURIComponent(e))+".json",a=n.join(this.actualBaseCachePath,t);return{dirPath:a,dataPath:n.join(a,r),metaPath:n.join(a,r.replace(".json",".meta.json"))}}async getData(e,t,r={},a=!1){const n=`${this.basePath}/${e}`,{dirPath:s,dataPath:i,metaPath:c}=this.getFilePaths(e,t);if(!a){const e=this.checkAndReadFromCache(i,c);if(null!==e)return e}try{const e=await fetch(n,r);if(!e.ok)throw new Error(`HTTP error: ${e.status}`);const t=await e.json();return this.ensureDirExists(s),this.writeJSON(i,t),this.writeJSON(c,{lastFetched:Date.now()}),t}catch(e){console.warn(`Fetch failed for ${n}, trying cache fallback...`);const t=this.readJSONSafe(i);if(t)return t;throw console.error("Cache fallback also failed:",e),e}}checkAndReadFromCache(e,t){if(!a.existsSync(e))return null;if(!this.maxAge)return this.readJSONSafe(e);const r=this.readJSONSafe(t);if(!r?.lastFetched)return this.readJSONSafe(e);return(Date.now()-r.lastFetched)/1e3<this.maxAge?this.readJSONSafe(e):null}ensureDirExists(e){a.existsSync(e)||a.mkdirSync(e,{recursive:!0})}}; //# sourceMappingURL=index.js.map