首页 > 解决方案 > 如何在 dexie.js 中为文件系统建模?

问题描述

我正在尝试使用 dexie.js 创建一个虚拟文件系统。每个文件和目录至少有 2 个属性,id 和 name。此外,文件将具有包含文件内容的 blob 属性。但是,我不知道是将目录的子级存储为目录的多值索引,还是将父级引用为文件的索引。哪个是更好的选择?

我过去的 SQL 经验告诉我选择后者,但我不知道 IndexedDB 哪种情况会处理得更好。

标签: filesystemsindexeddbdexie

解决方案


我会推荐一个层次结构,如下所示:

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);
  });
}

推荐阅读