cachified-adapter-sqlite
Version:
SQLite adapter for @epic-web/cachified. Compatible with better-sqlite3, sqlite, sqlite3, node:sqlite, and bun:sqlite.
59 lines (56 loc) • 1.67 kB
JavaScript
import { b as buildCacheKey, t as totalTtl } from './cache-key-CFVg9mcK.js';
function sqliteCacheAdapter(options) {
return {
name: options.name ?? "sqlite",
get: async (key) => {
const cacheKey = buildCacheKey(key, options.keyPrefix);
const row = await options.database.get(
`SELECT value, metadata FROM ${options.tableName} WHERE key = ?`,
cacheKey
);
if (!row) {
return null;
}
const entry = {
value: JSON.parse(row.value),
metadata: JSON.parse(row.metadata)
};
if (!entry.value) {
return null;
}
return entry;
},
set: async (key, entry) => {
const cacheKey = buildCacheKey(key, options.keyPrefix);
const ttl = totalTtl(entry.metadata);
await options.database.run(
`INSERT OR REPLACE INTO ${options.tableName} (key, value, metadata) VALUES (?, ?, ?)`,
[
cacheKey,
JSON.stringify(entry.value),
JSON.stringify({
...entry.metadata,
ttl: ttl === Number.POSITIVE_INFINITY ? null : ttl
})
]
);
return entry.value;
},
delete: async (key) => {
const cacheKey = buildCacheKey(key, options.keyPrefix);
await options.database.run(
`DELETE FROM ${options.tableName} WHERE key = ?`,
cacheKey
);
}
};
}
function createSqliteCacheTable(database, tableName) {
return database.exec(`CREATE TABLE IF NOT EXISTS ${tableName} (
key TEXT PRIMARY KEY,
value TEXT,
metadata TEXT
)`);
}
export { createSqliteCacheTable, sqliteCacheAdapter };
//# sourceMappingURL=sqlite.js.map