brendmanager/tests/helpers.ts
2026-11-15 14:44:19 +05:00

35 lines
1.2 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { PGlite } from "@electric-sql/pglite";
import { buildApp } from "../src/app.js";
import { migrate, type Db, type Queryable } from "../src/db.js";
export const TOKEN = "mock-owner-token";
/** Postgres в WASM (PGlite) с тем же интерфейсом Db, что и боевой pg. */
export function createMockDb(): Db {
const pg = new PGlite();
const wrap = (c: { query: PGlite["query"]; exec: PGlite["exec"] }): Queryable => ({
async query<T>(sql: string, params?: unknown[]) {
if (params === undefined) {
const r = await c.exec(sql);
return (r[r.length - 1]?.rows ?? []) as T[];
}
return (await c.query(sql, params)).rows as T[];
},
});
const base = wrap(pg as never);
return {
...base,
tx: (fn) => pg.transaction((t) => fn(wrap(t as never))),
close: () => pg.close(),
};
}
export async function setup() {
const db = createMockDb();
await migrate(db);
const app = buildApp({ db, apiToken: TOKEN });
const call = (method: "GET" | "POST" | "PATCH", url: string, payload?: unknown, token: string | null = TOKEN) =>
app.inject({ method, url, payload: payload as object, headers: token ? { authorization: `Bearer ${token}` } : {} });
return { db, app, call };
}