feat(api): 开发auth、login等接口,规范格式化

This commit is contained in:
R524809
2026-09-03 13:11:06 +08:00
parent 195b6d25e9
commit 037928c778
82 changed files with 9199 additions and 5236 deletions
+59
View File
@@ -0,0 +1,59 @@
import { Pool, type PoolClient, type QueryResultRow } from 'pg';
export type DatabaseTransaction = Pick<PoolClient, 'query'>;
export class Database {
public constructor(private readonly pool: Pool) {}
public async transaction<T>(
work: (transaction: DatabaseTransaction) => Promise<T>,
): Promise<T> {
const client = await this.pool.connect();
try {
await client.query('BEGIN');
// atlas_app_login is NOINHERIT by design; application DML always uses the least-privileged group role.
await client.query('SET LOCAL ROLE atlas_app');
const result = await work(client);
await client.query('COMMIT');
return result;
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
}
/** Every tenant-scoped query must run through this method. */
public async workspaceTransaction<T>(
workspaceId: string,
work: (transaction: DatabaseTransaction) => Promise<T>,
): Promise<T> {
return this.transaction(async (transaction) => {
// SET LOCAL is scoped to this transaction and cannot leak a tenant id through the pool.
await transaction.query(
"SELECT set_config('app.workspace_id', $1, true)",
[workspaceId],
);
return work(transaction);
});
}
public async query<Row extends QueryResultRow = QueryResultRow>(
text: string,
values?: unknown[],
) {
// Even non-tenant reads use the restricted role; callers cannot accidentally use the login role's privileges.
return this.transaction((transaction) =>
transaction.query<Row>(text, values),
);
}
public async close() {
await this.pool.end();
}
}
export function createApplicationDatabase(connectionString: string): Database {
return new Database(new Pool({ connectionString, max: 10 }));
}