filesystems - 如何在 dexie.js 中为文件系统建模?
问题描述
我正在尝试使用 dexie.js 创建一个虚拟文件系统。每个文件和目录至少有 2 个属性,id 和 name。此外,文件将具有包含文件内容的 blob 属性。但是,我不知道是将目录的子级存储为目录的多值索引,还是将父级引用为文件的索引。哪个是更好的选择?
我过去的 SQL 经验告诉我选择后者,但我不知道 IndexedDB 哪种情况会处理得更好。
解决方案
我会推荐一个层次结构,如下所示:
const db = new Dexie('filesystem');
db.version(1).stores({
files: `
[parentDir+name],
parentDir`
});
通过使用复合索引 [parentDir+name],数据库将确保没有两个项目共享相同的路径。
通过索引 parentDir,您可以仅使用索引列出直接子级和递归子级。
一些例子:
function createDir(parentDir, name) {
// The following transaction will fail if
// the combination parentDir+name already exists or
// represents a file.
return db.files.add({parentDir, name, type: "dir"});
}
function createFile(parentDir, filename, blob) {
return db.transaction('rw', db.files, async ()=>{
// Verify parentDir exists and is a directory:
const dir = await db.files.get({
parentDir: parentDir
});
if (!dir) throw new Error("Parent dir not found");
if (dir.type !== 'dir') throw new Error("Parent is not a dir");
await db.files.add({
type: 'file',
name: filename,
parentDir,
blob
});
});
}
/** List all files and folders within given diretory */
function listDirectory(dirPath) {
return db.files
.where({parentDir: dirPath})
.toArray();
}
/** List all files and folders recursively within given diretory */
function listDirectoryRecursively(dirPath) {
return db.files
.where('parentDir')
.startsWith(dirPath)
.toArray();
}
移动文件或目录将很快,因为您可以在单个查询中到达整个子树。
function moveDirectory (oldParentDir, name, newParentDir) {
return db.transaction('rw', db.files, async ()=>{
// Move the directory itself:
await db.files
.where({parentDir: oldParentDir, name: name})
.modify(item => item.parentDir = newDir);
// Move all descendants:
await db.files
.where('parentDir')
.startsWith(oldParentDir + "/" + name)
.modify(item =>
item.parentDir = newParentDir +
item.parentDir.substr(oldParentDir.length) + // strip start
"/" + item.name);
});
}
推荐阅读
- sql - T-SQL UPDATE 语句影响的记录少于 select 语句
- javascript - ckeditor第一次尝试不发送数据,初始值没有更新?
- python - sklearn.metrics 中产生的精度和召回率错误的 F1 分数
- c# - 将字符串转换或显示为货币
- deepsecurity - 如何在 Python 代码中为 Trend v12 DSM SAAS API 调用传递反恶意软件电子邮件自定义值
- node.js - Hapi catbox 无法连接到 redis 服务器
- javascript - 如何从 JavaScript 中的对象数组中选择属性?
- python-3.x - 将文件路径保存到变量时出现语法错误
- vagrant - vagrant up 不运行进度状态:E_INVALIDARG VBoxManage.exe:错误:设备导入失败
- azure - Azure 自动化 Runbook 缺少必需参数