存储适配器告诉引擎文档放在哪里。无论是 Fabric.js 保存到数据库、保存到浏览器,还是存到其他地方,都靠它。整个过程不依赖任何托管服务。
内置适配器
import {
createLocalStorage,
createMemoryStorage,
} from "fabricjs-document-engine/storage";
const engine = createDocumentEngine({
canvas,
storage: createLocalStorage({ prefix: "my-app:" }),
autosave: true,
});
await engine.load("project-42");
await engine.save();| 适配器 | 文档存放位置 | 适合 |
|---|---|---|
createLocalStorage() | 浏览器的 localStorage | 原型和离线工具 |
createMemoryStorage() | 内存,刷新即丢失 | 测试和演示 |
createKeyValueStorage(store, prefix) | 你传入的任意键值存储 | sessionStorage 等 |
这三个都会检查修订号,支持版本,并提供 listDocuments() 和 deleteDocument(id):
const storage = createLocalStorage({ prefix: "my-app:" });
const ids = await storage.listDocuments();
await storage.deleteDocument("old-draft");localStorage 每个网站大约只有 5 MB。图很大或文档很多时,请保存到你自己的后端。
任意键值存储
createKeyValueStorage 在任何同步存储之上加上修订号检查、列表和版本:
import { createKeyValueStorage } from "fabricjs-document-engine/storage";
const sessionStore = createKeyValueStorage(
{
read: (key) => sessionStorage.getItem(key),
write: (key, value) => sessionStorage.setItem(key, value),
remove: (key) => sessionStorage.removeItem(key),
keys: () => Object.keys(sessionStorage),
},
"my-app:"
);Fabric.js 保存到数据库
在真实产品里,为你的 REST API 写一个存储适配器,只要两个函数:
import type { DocumentStorage } from "fabricjs-document-engine";
const storage: DocumentStorage = {
async loadDocument(id) {
const response = await fetch(`/api/documents/${id}`);
return response.json();
},
async saveDocument(document, { expectedRevision, signal }) {
await fetch(`/api/documents/${document.id}`, {
method: "PUT",
headers: { "If-Match": String(expectedRevision ?? "*") },
body: JSON.stringify(document),
signal,
});
},
};这个简化版省略了错误处理。自定义后端给出了完整的适配器,包括冲突、重试,以及让 Fabric.js 保存到数据库更安全的 SQL。写完后请检查适配器。