Last active
September 4, 2024 07:20
-
-
Save IlanFrumer/46f4cacd57f2046ae311e832a625200e to your computer and use it in GitHub Desktop.
node:sqlite
This file contains 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
import { DatabaseSync } from "node:sqlite"; | |
export class Fetcher { | |
private database: DatabaseSync; | |
constructor() { | |
this.database = new DatabaseSync('cache.db', { open: true }); | |
this.database.exec(` | |
CREATE TABLE IF NOT EXISTS cache ( | |
uri TEXT PRIMARY KEY, | |
body TEXT | |
) STRICT; | |
`); | |
} | |
async get(uri: string) { | |
const query = this.database.prepare("SELECT body FROM cache WHERE uri = ?"); | |
const res = query.get(uri) as { body: string } | undefined; | |
let body = res?.body ?? null; | |
if (body == null) { | |
body = await fetch(uri).then((res) => res.text()); | |
if (body == null) throw new Error(`Failed to fetch ${uri}`); | |
this.database | |
.prepare("INSERT INTO cache (uri, body) VALUES (?, ?)") | |
.run(uri, body); | |
} | |
return body; | |
} | |
} | |
This file contains 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
{ | |
"ext": ".ts", | |
"exec": "node --experimental-strip-types --experimental-sqlite --disable-warning=ExperimentalWarning" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment