搭建应用
应用只查询 Runtime Database,不读取正在编辑的 Workspace。根据部署方式选择 Embedded 或 Remote,两者返回相同的高层 RuntimeDatabase API。
选择连接模式
- Embedded:单个长期 Node.js 进程拥有本地持久磁盘,并且没有其他 Server 打开同一个 Database。
- Remote:Local Server 已经持有 Writer Lock,或者 Web 应用、多个进程和其他语言需要共享一个 Writer Host。
- Serverless 多实例不能分别使用 Embedded 打开同一个本地目录;应该连接独立的持久 Server。
Embedded TypeScript
npm install md-db-engine@0.3.0import { openDatabase } from 'md-db-engine'
const database = await openDatabase({ path: './content.mddb' })
const documents = database.collection('documents')
const published = await documents.find({
where: { field: 'status', operator: 'eq', value: 'published' },
orderBy: [{ field: 'title', direction: 'asc' }],
limit: 20,
})
await documents.patch(published.records[0].id, { status: 'archived' })
await database.close()在开发热更新环境中复用一个进程级 Promise,不要为每次请求重复调用 openDatabase()。应用关闭时调用 close()。
Remote TypeScript
import { createRemoteClient } from 'md-db-engine'
const database = await createRemoteClient('http://127.0.0.1:3000', {
credentials: process.env.MDDB_CREDENTIALS,
})
const result = await database.collection('documents').find({ limit: 20 })
console.log(result.records)
await database.close()Credential 应该来自环境变量或 Secret Manager,不能进入浏览器代码、Workspace 或 Git。浏览器应用通常通过自己的受控服务端调用数据库,而不是向每个访客公开 Owner Credential。
使用迁移生成的 Schema
迁移 Config 决定初始 Collection 和 Schema。应用应该把 Collection 名称和字段契约作为自己的类型边界,而不是依据 Markdown 所在目录推断业务类型。目录可以用于 Obsidian 导航,多个目录可以属于同一个 documents Collection。
Next.js 结构
仓库的 example/blog 展示 Embedded 模式。生产应用至少分离三个职责:
lib/database.ts # 连接与 Writer 生命周期
lib/documents.ts # 查询和 Mutation Repository
app/ # 页面与 Route Handler测试使用独立临时 Database,并验证创建、查询、Mutation、关闭和重新打开。Remote 变体还应该在测试中启动 Local Server,使用 Editor Credential 执行查询和受控 Mutation。