UNPKG

unstorage

Version:
77 lines (76 loc) 2.38 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); module.exports = void 0; var _utils = require("./utils/index.cjs"); var _database = require("@planetscale/database"); var _nodeFetchNative = require("node-fetch-native"); var _default = (0, _utils.defineDriver)((opts = {}) => { if (!opts.url) throw new Error("Database URL is required to use the Planetscale driver."); opts.table = opts.table || "storage"; let _connection; const getConnection = () => { if (!_connection) { _connection = (0, _database.connect)({ url: opts.url, fetch: _nodeFetchNative.fetch }); if (opts.boostCache) { _connection.execute("SET @@boost_cached_queries = true;").catch(error => { console.error("[unstorage] [planetscale] Failed to enable cached queries:", error); }); } } return _connection; }; return { name: "planetscale", options: opts, hasItem: async key => { const res = await getConnection().execute(`SELECT COUNT(id) from ${opts.table} WHERE id=:key;`, { key }); return res.size >= 0; }, getItem: async key => { const res = await getConnection().execute(`SELECT value from ${opts.table} WHERE id=:key;`, { key }); return rows(res)[0]?.value ?? null; }, setItem: async (key, value) => { await getConnection().execute(`INSERT INTO ${opts.table} (id, value) VALUES (:key, :value) ON DUPLICATE KEY UPDATE value = :value;`, { key, value }); }, removeItem: async key => { await getConnection().execute(`DELETE FROM ${opts.table} WHERE id=:key;`, { key }); }, getMeta: async key => { const res = await getConnection().execute(`SELECT created_at, updated_at from ${opts.table} WHERE id=:key;`, { key }); return { birthtime: rows(res)[0]?.created_at, mtime: rows(res)[0]?.updated_at }; }, getKeys: async (base = "") => { const res = await getConnection().execute(`SELECT id from ${opts.table} WHERE id LIKE :base;`, { base: `${base}%` }); return rows(res).map(r => r.id); }, clear: async () => { await getConnection().execute(`DELETE FROM ${opts.table};`); } }; }); module.exports = _default; function rows(res) { return res.rows || []; }