Skip to content

Instantly share code, notes, and snippets.

@IlanFrumer
Last active September 4, 2024 07:20
Show Gist options
  • Save IlanFrumer/46f4cacd57f2046ae311e832a625200e to your computer and use it in GitHub Desktop.
Save IlanFrumer/46f4cacd57f2046ae311e832a625200e to your computer and use it in GitHub Desktop.
node:sqlite
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;
}
}
{
"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