Created
November 3, 2023 21:12
-
-
Save alexberkowitz/70c34626b073ff4131dbf33af0e39b76 to your computer and use it in GitHub Desktop.
Scriptable Cache script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Variables used by Scriptable. | |
// These must be at the very top of the file. Do not edit. | |
// icon-color: deep-gray; icon-glyph: magic; | |
// Hosting the Cache script myself to make it easier to find for those using my scripts :) | |
// NOTE: This script was written by evandcoleman: https://github.com/evandcoleman/scriptable | |
class Cache { | |
constructor(name) { | |
this.fm = FileManager.iCloud(); | |
this.cachePath = this.fm.joinPath(this.fm.documentsDirectory(), name); | |
if (!this.fm.fileExists(this.cachePath)) { | |
this.fm.createDirectory(this.cachePath); | |
} | |
} | |
async read(key, expirationMinutes) { | |
try { | |
const path = this.fm.joinPath(this.cachePath, key); | |
await this.fm.downloadFileFromiCloud(path); | |
const createdAt = this.fm.creationDate(path); | |
if (expirationMinutes) { | |
if ((new Date()) - createdAt > (expirationMinutes * 60000)) { | |
this.fm.remove(path); | |
return null; | |
} | |
} | |
const value = this.fm.readString(path); | |
try { | |
return JSON.parse(value); | |
} catch (error) { | |
return value; | |
} | |
} catch (error) { | |
return null; | |
} | |
} | |
write(key, value) { | |
const path = this.fm.joinPath(this.cachePath, key.replace('/', '-')); | |
console.log(`Caching to ${path}...`); | |
if (typeof value === 'string' || value instanceof String) { | |
this.fm.writeString(path, value); | |
} else { | |
this.fm.writeString(path, JSON.stringify(value)); | |
} | |
} | |
} | |
module.exports = Cache; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment