@jbrowse/core
Version:
JBrowse 2 core libraries used by plugins
69 lines (68 loc) • 2.06 kB
JavaScript
import { openDB } from 'idb';
const DB_NAME = 'jbrowse-file-handles';
const DB_VERSION = 1;
const STORE_NAME = 'handles';
let dbPromise;
function getDB() {
if (!dbPromise) {
dbPromise = openDB(DB_NAME, DB_VERSION, {
upgrade(db) {
if (!db.objectStoreNames.contains(STORE_NAME)) {
db.createObjectStore(STORE_NAME);
}
},
});
}
return dbPromise;
}
export function isFileSystemAccessSupported() {
return typeof window !== 'undefined' && 'showOpenFilePicker' in window;
}
let counter = 0;
export async function storeFileHandle(handle) {
const handleId = `fh${Date.now()}-${counter++}`;
const db = await getDB();
await db.put(STORE_NAME, {
handle,
name: handle.name,
createdAt: Date.now(),
}, handleId);
return handleId;
}
export async function getFileHandle(handleId) {
const db = await getDB();
const entry = await db.get(STORE_NAME, handleId);
return entry?.handle;
}
export async function removeFileHandle(handleId) {
const db = await getDB();
await db.delete(STORE_NAME, handleId);
}
export async function verifyPermission(handle, requestPermission = false) {
const options = { mode: 'read' };
const currentPermission = await handle.queryPermission(options);
if (currentPermission === 'granted') {
return true;
}
if (requestPermission) {
const newPermission = await handle.requestPermission(options);
if (newPermission === 'granted') {
return true;
}
}
return false;
}
export async function cleanupStaleHandles(maxAgeMs) {
const db = await getDB();
const now = Date.now();
const tx = db.transaction(STORE_NAME, 'readwrite');
const store = tx.objectStore(STORE_NAME);
let cursor = await store.openCursor();
while (cursor) {
if (now - cursor.value.createdAt > maxAgeMs) {
await cursor.delete();
}
cursor = await cursor.continue();
}
await tx.done;
}