Skip to content

数据存储 ​

插件有三种地方存数据:键值存储 dbStorage、文档数据库 db,以及插件自己的数据目录。都不需要权限,数据只有本插件能访问。

怎么选 ​

要存的东西用例子
单个设置、偏好、上次的状态ling.dbStorage主题、排序方式、上次打开的标签页
一组记录,要增删改查ling.db,每条记录一个文档便签、书签、历史记录
记录附带的二进制(≤ 10 MiB)ling.db 的附件便签里的图片
大文件、缓存、数据库文件数据目录 + ling.fs下载的图标、SQLite 文件
只在这次运行里用的中间文件临时目录 + ling.fs转码中间产物

dbStorage:键值 ​

ts
await window.ling.dbStorage.setItem('sort', 'mtime')
const sort = (await window.ling.dbStorage.getItem('sort')) ?? 'name'
await window.ling.dbStorage.removeItem('sort')
  • 值可以是任意 JSON,序列化后不超过 1 MiB;读不到时为 null。
  • 不适合存一组记录:每次改一条都要整体读写,还会互相覆盖。

db:文档数据库 ​

语义和 PouchDB / uTools 的 db 一致:每个文档是一个 JSON 对象,有 _id 和版本号 _rev。

ts
// 新建:不带 _rev
const res = await window.ling.db.put({ _id: 'note/1', title: '买牛奶', done: false })
// res = { id: 'note/1', rev: '1-…', ok: true }

// 读取:不存在时为 null
const doc = await window.ling.db.get('note/1')

// 更新:必须带上当前的 _rev,否则为 conflict
await window.ling.db.put({ ...doc, done: true })

// 按前缀列出(结果按 _id 排序)
const notes = await window.ling.db.allDocs('note/')

// 删除
await window.ling.db.remove('note/1')

要点:

  • 写操作不会 reject:失败时返回 { error: true, name, message },name 为 conflict(版本不对)、not_found(不存在)或 exception。记得检查返回值。
  • _id 用「类型前缀 + 唯一 ID」的形式(如 note/<uuid>),方便用 allDocs('note/') 按类型列出。
  • 单个文档序列化后不超过 1 MiB;_id 不超过 1024 字节。
  • bulkDocs(docs) 在一个事务里批量写入,_deleted: true 的文档按删除处理,逐项返回结果。
  • 附件:postAttachment(id, bytes, mimeType) 每个文档一个、不超过 10 MiB、只能新建不能覆盖;用 getAttachment(id) 读取。

在 Vue 里用 ​

@lingtools/plugin-sdk/vue 把上面两种存储包装成响应式数据,处理好了读取时机、写入排队和版本冲突。

一个设置:useDbStorage

ts
import { useDbStorage } from '@lingtools/plugin-sdk/vue'

const sort = useDbStorage('sort', 'mtime')
// 一开始是默认值,读完换成存储里的值;像普通 ref 一样读写,修改会自动保存
sort.value = 'name'
await sort.ready // 需要确保已读完时

可选项:device: true 按设备分开存(比如本机路径),platform: true 按平台分开存,debounce 写入防抖,parse 校验读出的值。同一个键只在一处调用 useDbStorage,其他地方通过 props 或 store 共享,否则会互相覆盖。

一组记录:useDbCollection,每条记录存成一个文档 <前缀><uuid>

ts
import { useDbCollection } from '@lingtools/plugin-sdk/vue'

interface Note { _id: string; _rev?: string; title: string; updatedAt: number }

const notes = useDbCollection<Note>('note/', {
  parse: (raw) => (typeof raw.title === 'string' ? (raw as Note) : null),
  sort: (a, b) => b.updatedAt - a.updatedAt,
})

await notes.load()                       // 读出全部
notes.items.value                        // 排好序的列表(只读)
await notes.create({ title: '买牛奶', updatedAt: Date.now() })
await notes.update(id, (note) => ({ ...note, title: '买酸奶' })) // 冲突时自动重读重试
await notes.remove(id)

数据目录与临时目录 ​

ts
const dataDir = await window.ling.getPluginLocalDataPath()
const tempDir = await window.ling.getPluginTempPath()
await window.ling.fs.writeFile(`${dataDir}/cache.json`, JSON.stringify(cache))
目录保留多久
数据目录长期保留。卸载插件时由用户选择是否一起删除
临时目录插件结束运行(销毁)或 lingtools 退出时清空;退到后台时保留

用 ling.fs 读写这两个目录不需要任何权限。

数据归属 ​

  • 每个插件的数据互相隔离,插件拿不到别的插件的数据。
  • 开发版(dev-<name>)和正式版(<name>)的数据也是分开的,开发时不会弄乱自己正在用的正式版数据。
  • 多实例插件的各个实例共享同一份数据。
  • 用户可以在 lingtools 设置的「数据」分类里查看、删除每个插件的文档和附件。