##2025/3/27 06:52:46:
cloudflare memoflow 更新数据库表,将gitthub app auth 数据存入数据库
这次更改包含两次提交
第一次提交:
https://github.com/qyzhizi/hono-auth-test-app-D1-func/commit/97084b6fceb1dac0b8f63b9743a0eab4885f2e87
在这个提交中,更新了数据库的定义文件,新添加了一些存储 github app auth 信息的表,比如:
user_settings githubAccess
具体执行步骤见: @更新 cloudflare hono drizzle 数据库步骤
更新 cloudflare hono drizzle 数据库步骤
pnpm drizzle-kit generate --config=drizzle-dev.config.ts
npx wrangler d1 migrations apply hono_db1 --local
npx wrangler d1 migrations apply hono_db1 --remote
由于更新了
https://github.com/qyzhizi/hono-auth-test-app-D1-func/blob/97084b6fceb1dac0b8f63b9743a0eab4885f2e87/src/infrastructure/db/schema.ts
这个数据库文件,需要生成数据库迁移文件,由命令 pnpm drizzle-kit generate --config=drizzle-dev.config.ts
生成
例如:
https://github.com/qyzhizi/hono-auth-test-app-D1-func/blob/97084b6fceb1dac0b8f63b9743a0eab4885f2e87/drizzle/migrations/0001_sleepy_diamondback.sql
然后将更新数据库:
npx wrangler d1 migrations apply hono_db1 --local
npx wrangler d1 migrations apply hono_db1 --remote
然后再在 cloudflare d1 上查看数据库文件,发现 user_auths 是没有更新成功的,而 users 表的记录有点问题,就删除了有问题的唯一行记录
第二次提交:
https://github.com/qyzhizi/hono-auth-test-app-D1-func/commit/82798a8a383ee76dce986045ad83fa1bcec9898b
在这个提交中,更新了对数据库的操作,在获取 GitHub app access token 的过程中将 access token 的相关信息存入了数据库
在中间件中,将 userid 存储到 c.env 中 ,方便后续随时读取
c.env.USER_ID = accessTokenPayload.sub;
在对数据库操作的过程中遇到两个问题
第一个问题
使用 drizzle-orm 操作字段名时,使用的是在文件 src/infrastructure/db/schema.ts 中定义的字段名,而不是数据库实际的字段名,例如应该使用 accessToken 而不是 access_token
export const githubAppAccess = sqliteTable("github_access", {
id: text("id").primaryKey(),
userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
githubRepoName: text("github_repo_name", { length: 255 }),
currentSyncFile: text("current_sync_file", { length: 512 }),
otherSyncFileList: text("other_sync_file_list"),
accessToken: text("access_token", { length: 255 }),
accessTokenExpiresAt: integer("access_token_expires_at", { mode: "timestamp" }),
refreshToken: text("refresh_token", { length: 255 }),
refreshTokenExpiresAt: integer("refresh_token_expires_at", { mode: "timestamp" }),
githubUserName: text("github_user_name", { length: 255 }),
});
Drizzle-orm 设计上会以你在 TypeScript 文件中定义的字段名作为操作接口的标识符,而不是直接使用数据库中的物理列名
第二个问题
另外存入数据表时,数据类型需要注意,比如 timestamp,accessTokenExpiresAt 字段的类型就是 timestamp,因此构建字段的数据类型如下:
const tokenData = await fetchAccessToken(CLIENT_ID, CLIENT_SECRET, code)
const filteredTokenData: Record<string, any> = {
accessToken: tokenData.access_token,
accessTokenExpiresAt: new Date(Date.now() + tokenData.expires_in * 1000), // 8小时后过期,
refreshToken: tokenData.refresh_token,
refreshTokenExpiresAt: new Date(Date.now() + tokenData.refresh_token_expires_in * 1000) // 184天后过期
};
// 尝试更新数据库中 GitHub App 相关数据
try {
await addOrUpdategithubAppAccessData(c, c.env.USER_ID, filteredTokenData)
} catch (dbError) {
console.error('更新 GitHub App 访问数据时出错:', dbError)
return c.json({ error: '更新 GitHub App 访问数据失败' }, 500)
}