bentocache
Version:
Multi-tier cache module for Node.js. Redis, Upstash, CloudfareKV, File, in-memory and others drivers
77 lines (76 loc) • 2.8 kB
JavaScript
import {
DatabaseDriver
} from "../../../../chunk-CVIVKJ25.js";
import "../../../../chunk-YAGCWAYQ.js";
import "../../../../chunk-BO75WXSS.js";
// src/drivers/database/adapters/kysely.ts
import { SqliteAdapter, MysqlAdapter } from "kysely";
function kyselyDriver(options) {
return {
options,
factory: (config) => {
const adapter = new KyselyAdapter(config);
return new DatabaseDriver(adapter, config);
}
};
}
var KyselyAdapter = class {
#dialect;
#tableName;
#connection;
constructor(config) {
this.#connection = config.connection;
const adapter = this.#connection.getExecutor().adapter;
if (adapter instanceof SqliteAdapter) {
this.#dialect = "sqlite";
} else if (adapter instanceof MysqlAdapter) {
this.#dialect = "mysql";
} else {
this.#dialect = "pg";
}
}
setTableName(tableName) {
this.#tableName = tableName;
}
async get(key) {
const result = await this.#connection.selectFrom(this.#tableName).select(["value", "expires_at"]).where("key", "=", key).executeTakeFirst();
if (!result) return;
return { value: result.value, expiresAt: result.expires_at };
}
async delete(key) {
const result = await this.#connection.deleteFrom(this.#tableName).where("key", "=", key).executeTakeFirst();
return result.numDeletedRows > 0;
}
async deleteMany(keys) {
const result = await this.#connection.deleteFrom(this.#tableName).where("key", "in", keys).executeTakeFirst();
return +result.numDeletedRows.toString();
}
async disconnect() {
await this.#connection.destroy();
}
async createTableIfNotExists() {
await this.#connection.schema.createTable(this.#tableName).addColumn("key", "varchar(255)", (col) => col.primaryKey().notNull()).addColumn("value", "text").addColumn("expires_at", "bigint").ifNotExists().execute();
}
async pruneExpiredEntries() {
await this.#connection.deleteFrom(this.#tableName).where("expires_at", "<", Date.now()).execute();
}
async clear(prefix) {
await this.#connection.deleteFrom(this.#tableName).where("key", "like", `${prefix}%`).execute();
}
async set(row) {
const expiresAt = this.#dialect === "sqlite" ? row.expiresAt?.getTime() : row.expiresAt;
await this.#connection.insertInto(this.#tableName).values({ key: row.key, value: row.value, expires_at: expiresAt ?? null }).$if(
this.#dialect === "mysql",
(query) => query.onDuplicateKeyUpdate({ value: row.value, expires_at: expiresAt })
).$if(this.#dialect !== "mysql", (query) => {
return query.onConflict((conflict) => {
return conflict.columns(["key"]).doUpdateSet({ value: row.value, expires_at: expiresAt });
});
}).execute();
}
};
export {
KyselyAdapter,
kyselyDriver
};
//# sourceMappingURL=kysely.js.map