eyrun-api/tests/helpers.ts
2026-02-08 11:43:06 +01:00

63 lines
1.7 KiB
TypeScript

import { type FastifyInstance } from "fastify";
import { buildApp } from "../src/app.js";
import { db } from "../src/db/index.js";
import { users, otpCodes, sessions, accounts, memberships, projects, wms, packages } from "../src/db/schema.js";
import { sql } from "drizzle-orm";
export async function createTestApp(): Promise<FastifyInstance> {
const app = buildApp();
await app.ready();
return app;
}
export async function cleanDb() {
await db.delete(wms);
await db.delete(packages);
await db.delete(projects);
await db.delete(sessions);
await db.delete(memberships);
await db.delete(accounts);
await db.delete(otpCodes);
await db.delete(users);
}
/** Request an OTP and return the code from the DB */
export async function requestOtpCode(app: FastifyInstance, email: string): Promise<string> {
await app.inject({ method: "POST", url: "/login", payload: { email } });
const [otp] = await db
.select()
.from(otpCodes)
.where(sql`${otpCodes.email} = ${email}`)
.orderBy(sql`${otpCodes.createdAt} desc`)
.limit(1);
return otp.code;
}
/** Full signup flow: request OTP → signup → return response */
export async function signupUser(
app: FastifyInstance,
email: string,
accountName: string,
) {
const code = await requestOtpCode(app, email);
const res = await app.inject({
method: "POST",
url: "/signup",
payload: { email, code, accountName },
});
return res;
}
/** Full login flow for an existing user: request OTP → create session → return response */
export async function loginUser(app: FastifyInstance, email: string) {
const code = await requestOtpCode(app, email);
const res = await app.inject({
method: "POST",
url: "/sessions",
payload: { email, code },
});
return res;
}