在 Next.js 中集成 SQLite

1 分钟
目录

在 Next.js 中集成 SQLite

better-sqlite3 提供同步 API,配合服务端渲染非常直接。

复用连接

开发模式热重载会重复执行模块,把连接挂到 globalThis 上避免重复打开:

declare global {
  var __blogDb: Database.Database | undefined;
}

export function getDb() {
  if (!globalThis.__blogDb) {
    globalThis.__blogDb = new Database(dbPath);
  }
  return globalThis.__blogDb;
}

用 JSON 数组存标签

标签以 JSON 数组写入 tags 字段,查询时借助 SQLite 的 JSON 函数:

SELECT * FROM posts
WHERE EXISTS (
  SELECT 1 FROM json_each(posts.tags) WHERE json_each.value = ?
);
能力说明
事务db.transaction()
预编译db.prepare()
WALpragma('journal_mode = WAL')

评论(0

还没有评论,来抢沙发。

提交后需管理员审核通过才会显示。
在 Next.js 中集成 SQLite · Rosercode Blog