feat: 后端 SQLite→PostgreSQL 迁移(双驱动)——codes/showcase/sync/chibi/payment/security 全链路支持 pg,修复 grant 保留字,schema 双 DDL 导出
This commit is contained in:
1 parent
346f41d391
commit
605af4cdd3
17 files changed
+1516
-2202
No files matched your search
@@ -1,7 +1,7 @@
|
||||
import { Router } from "express";
|
||||
import type { Request, Response } from "express";
|
||||
import type Database from "better-sqlite3";
|
||||
import { getDb } from "../db/index.js";
|
||||
import type { Db } from "../db/index.js";
|
||||
import { getDb, dbAll, dbRun } from "../db/index.js";
|
||||
import { checkRedeemable, validateFormat, CodeError } from "../codes/service.js";
|
||||
import type { AccessInfo } from "../types/index.js";
|
||||
|
||||
@@ -36,16 +36,14 @@ function handleCodeError(res: Response, err: CodeError): void {
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the database instance: use injected DB if provided, otherwise
|
||||
* fall back to the global singleton.
|
||||
* Resolve the database instance.
|
||||
*/
|
||||
function resolveDb(injected?: Database.Database): Database.Database {
|
||||
function resolveDb(injected?: Db): Db {
|
||||
return injected ?? getDb();
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a device id: trim; reject anything not matching the format.
|
||||
* Throws a CodeError (400, "设备标识无效") on invalid input.
|
||||
*/
|
||||
function parseDeviceId(raw: string): string {
|
||||
const deviceId = raw.trim();
|
||||
@@ -55,6 +53,30 @@ function parseDeviceId(raw: string): string {
|
||||
return deviceId;
|
||||
}
|
||||
|
||||
// 双方言 SQL
|
||||
const BIND_SQL = {
|
||||
sqlite: "INSERT OR IGNORE INTO device_bindings (device_id, code) VALUES (?, ?)",
|
||||
pg: "INSERT INTO device_bindings (device_id, code) VALUES ($1, $2) ON CONFLICT (device_id, code) DO NOTHING",
|
||||
} as const;
|
||||
|
||||
const UNBIND_SQL = {
|
||||
sqlite: "DELETE FROM device_bindings WHERE device_id = ? AND code = ?",
|
||||
pg: "DELETE FROM device_bindings WHERE device_id = $1 AND code = $2",
|
||||
} as const;
|
||||
|
||||
const BINDINGS_SQL = {
|
||||
sqlite: `SELECT c.code, c.package_type, c.total_uses, c.used_uses, c.status
|
||||
FROM device_bindings b
|
||||
JOIN codes c ON c.code = b.code
|
||||
WHERE b.device_id = ?
|
||||
ORDER BY b.created_at, c.code`,
|
||||
pg: `SELECT c.code, c.package_type, c.total_uses, c.used_uses, c.status
|
||||
FROM device_bindings b
|
||||
JOIN codes c ON c.code = b.code
|
||||
WHERE b.device_id = $1
|
||||
ORDER BY b.created_at, c.code`,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Create the sync router (cloud-sync of redeemed code benefits).
|
||||
* Accepts an optional injected database for testing.
|
||||
@@ -62,40 +84,22 @@ function parseDeviceId(raw: string): string {
|
||||
* POST /api/sync/bind
|
||||
* Request: { deviceId: string, code: string }
|
||||
* Response: 200 { ok: true, access: AccessInfo }
|
||||
* 400 { error: "设备标识无效" / "兑换码格式不正确" / ... }
|
||||
* 404 { error: "兑换码不存在,请检查后重试" }
|
||||
* Idempotent: binding an already-bound code is a no-op success.
|
||||
*
|
||||
* GET /api/sync/restore?deviceId=XXX
|
||||
* Response: 200 { codes: BoundCode[] } (empty array when none)
|
||||
* 400 { error: "设备标识无效" }
|
||||
* Response: 200 { codes: BoundCode[] }
|
||||
*
|
||||
* POST /api/sync/unbind
|
||||
* Request: { deviceId: string, code: string }
|
||||
* Response: 200 { ok: true }
|
||||
* Idempotent: unbinding a non-existent binding still succeeds.
|
||||
*/
|
||||
export function createSyncRouter(injectedDb?: Database.Database): Router {
|
||||
export function createSyncRouter(injectedDb?: Db): Router {
|
||||
const router = Router();
|
||||
|
||||
const bindStmt = (db: Database.Database) =>
|
||||
db.prepare("INSERT OR IGNORE INTO device_bindings (device_id, code) VALUES (?, ?)");
|
||||
const unbindStmt = (db: Database.Database) =>
|
||||
db.prepare("DELETE FROM device_bindings WHERE device_id = ? AND code = ?");
|
||||
const bindingsStmt = (db: Database.Database) =>
|
||||
db.prepare(
|
||||
`SELECT c.code, c.package_type, c.total_uses, c.used_uses, c.status
|
||||
FROM device_bindings b
|
||||
JOIN codes c ON c.code = b.code
|
||||
WHERE b.device_id = ?
|
||||
ORDER BY b.created_at, c.code`,
|
||||
);
|
||||
|
||||
/**
|
||||
* POST /api/sync/bind
|
||||
* Bind a redeemed code to a device so it can be restored later.
|
||||
*/
|
||||
router.post("/bind", (req: Request, res: Response): void => {
|
||||
router.post("/bind", async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const { deviceId, code } = req.body as { deviceId?: string; code?: string };
|
||||
if (!deviceId || typeof deviceId !== "string") {
|
||||
@@ -109,10 +113,9 @@ export function createSyncRouter(injectedDb?: Database.Database): Router {
|
||||
const db = resolveDb(injectedDb);
|
||||
const id = parseDeviceId(deviceId);
|
||||
const normalized = validateFormat(code);
|
||||
// Verifies the code exists & is still redeemable (active, not expired,
|
||||
// not exhausted). Throws CodeError with Chinese message + status.
|
||||
const access: AccessInfo = checkRedeemable(db, normalized);
|
||||
bindStmt(db).run(id, access.code);
|
||||
// Verifies the code exists & is still redeemable
|
||||
const access: AccessInfo = await checkRedeemable(db, normalized);
|
||||
await dbRun(db, BIND_SQL, [id, access.code]);
|
||||
res.status(200).json({ ok: true, access });
|
||||
} catch (err) {
|
||||
if (err instanceof CodeError) {
|
||||
@@ -128,7 +131,7 @@ export function createSyncRouter(injectedDb?: Database.Database): Router {
|
||||
* GET /api/sync/restore?deviceId=XXX
|
||||
* Return all codes bound to this device with their access info.
|
||||
*/
|
||||
router.get("/restore", (req: Request, res: Response): void => {
|
||||
router.get("/restore", async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const deviceIdParam = req.query.deviceId;
|
||||
if (!deviceIdParam || typeof deviceIdParam !== "string") {
|
||||
@@ -137,7 +140,7 @@ export function createSyncRouter(injectedDb?: Database.Database): Router {
|
||||
}
|
||||
const db = resolveDb(injectedDb);
|
||||
const id = parseDeviceId(deviceIdParam);
|
||||
const rows = bindingsStmt(db).all(id) as BindingRow[];
|
||||
const rows = await dbAll<BindingRow>(db, BINDINGS_SQL, [id]);
|
||||
const codes: BoundCode[] = rows.map((row) => ({
|
||||
code: row.code,
|
||||
packageType: row.package_type,
|
||||
@@ -158,9 +161,9 @@ export function createSyncRouter(injectedDb?: Database.Database): Router {
|
||||
|
||||
/**
|
||||
* POST /api/sync/unbind
|
||||
* Remove a binding. Idempotent: succeeds even if the binding never existed.
|
||||
* Remove a binding. Idempotent.
|
||||
*/
|
||||
router.post("/unbind", (req: Request, res: Response): void => {
|
||||
router.post("/unbind", async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const { deviceId, code } = req.body as { deviceId?: string; code?: string };
|
||||
if (!deviceId || typeof deviceId !== "string") {
|
||||
@@ -174,7 +177,7 @@ export function createSyncRouter(injectedDb?: Database.Database): Router {
|
||||
const db = resolveDb(injectedDb);
|
||||
const id = parseDeviceId(deviceId);
|
||||
const normalized = validateFormat(code);
|
||||
unbindStmt(db).run(id, normalized);
|
||||
await dbRun(db, UNBIND_SQL, [id, normalized]);
|
||||
res.status(200).json({ ok: true });
|
||||
} catch (err) {
|
||||
if (err instanceof CodeError) {
|
||||
@@ -187,4 +190,4 @@ export function createSyncRouter(injectedDb?: Database.Database): Router {
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user