eyrun-api/tests/helpers.ts
2026-02-08 13:39:33 +01:00

74 lines
2.3 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);
}
/** Get the latest OTP code for an email from the DB */
async function getLatestOtpCode(email: string): Promise<string> {
const [otp] = await db
.select()
.from(otpCodes)
.where(sql`${otpCodes.email} = ${email}`)
.orderBy(sql`${otpCodes.createdAt} desc`)
.limit(1);
return otp.code;
}
/** Request an OTP via /login (requires existing user) 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 } });
return getLatestOtpCode(email);
}
/** Request an OTP via /signup and return the code from the DB */
export async function requestSignupOtpCode(app: FastifyInstance, email: string): Promise<string> {
await app.inject({ method: "POST", url: "/signup", payload: { email } });
return getLatestOtpCode(email);
}
/** Full signup flow: request OTP via /signup → verify via /signup/verify → return response */
export async function signupUser(
app: FastifyInstance,
email: string,
accountName: string,
username?: string,
) {
const code = await requestSignupOtpCode(app, email);
const res = await app.inject({
method: "POST",
url: "/signup/verify",
payload: { email, code, accountName, username: username ?? email.split("@")[0] },
});
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: "/login/verify",
payload: { email, code },
});
return res;
}