refactor: migrate backend to pnpm monorepo with Hono module architecture
- Replace Bun with pnpm 9 + Turborepo + tsx; apps/api renamed to apps/backend - Split backend into http/, modules/, lib/ layers mirroring tai-specguard - Add use-case + Result pattern, Problem Details RFC 7807, basePath /api/v1 - Mount Better Auth at /api/v1/auth, keep session-auth whitelist - Split Prisma schema into prisma/models/*, generate into generated/ - Rework packages/shared into lib/ + schemas/ with pagination DTOs - Implement health, groups, students, payments, waitlist modules - Add vitest suite with prisma mocks (21 tests), biome lint - Point web client to /api/v1/auth and /api/v1/groups/from-organization
This commit is contained in:
94
apps/backend/src/lib/email.ts
Normal file
94
apps/backend/src/lib/email.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import nodemailer, { type Transporter } from 'nodemailer'
|
||||
|
||||
type VerificationEmailData = { email: string; url: string; name?: string }
|
||||
type PasswordResetEmailData = { email: string; url: string; name?: string }
|
||||
type InvitationEmailData = { email: string; url: string; organizationName: string }
|
||||
|
||||
interface EmailProvider {
|
||||
sendVerificationEmail(data: VerificationEmailData): Promise<void>
|
||||
sendPasswordResetEmail(data: PasswordResetEmailData): Promise<void>
|
||||
sendOrganizationInvitation(data: InvitationEmailData): Promise<void>
|
||||
}
|
||||
|
||||
class SMTPEmailProvider implements EmailProvider {
|
||||
private transporter: Transporter
|
||||
|
||||
constructor() {
|
||||
this.transporter = nodemailer.createTransport({
|
||||
host: process.env.EMAIL_SERVER_HOST,
|
||||
port: Number(process.env.EMAIL_SERVER_PORT ?? 587),
|
||||
secure: (process.env.EMAIL_SERVER_PORT ?? '587') === '465',
|
||||
auth: {
|
||||
user: process.env.EMAIL_SERVER_USER,
|
||||
pass: process.env.EMAIL_SERVER_PASSWORD,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
private from() {
|
||||
return process.env.EMAIL_FROM ?? 'Gruperly <no-reply@gruperly.com>'
|
||||
}
|
||||
|
||||
private layout(title: string, body: string) {
|
||||
return `
|
||||
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 480px; margin: 0 auto; padding: 24px; color: #0a2540;">
|
||||
<h2 style="margin: 0 0 16px;">Gruperly</h2>
|
||||
<h3 style="margin: 0 0 8px;">${title}</h3>
|
||||
<p style="line-height: 1.6; color: #334155;">${body}</p>
|
||||
</div>
|
||||
`
|
||||
}
|
||||
|
||||
private async send(to: string, subject: string, html: string) {
|
||||
// Sin SMTP configurado (dev) no rompe el flujo: solo registra un aviso
|
||||
if (!process.env.EMAIL_SERVER_HOST) {
|
||||
console.warn(`[email] SMTP no configurado. Email no enviado a ${to}: "${subject}"`)
|
||||
return
|
||||
}
|
||||
await this.transporter.sendMail({ from: this.from(), to, subject, html })
|
||||
}
|
||||
|
||||
async sendVerificationEmail({ email, url, name }: VerificationEmailData) {
|
||||
const link = `<a href="${url}" style="display:inline-block;background:#1e90ff;color:#fff;text-decoration:none;padding:12px 24px;border-radius:12px;font-weight:600;">Verificar email</a>`
|
||||
await this.send(
|
||||
email,
|
||||
'Verifica tu email en Gruperly',
|
||||
this.layout(
|
||||
'Confirma tu dirección de email',
|
||||
`${name ? `Hola ${name}, ` : 'Hola, '}gracias por crear tu cuenta en Gruperly. Para empezar, verifica tu email con el botón de abajo (el enlace vence en 1 hora).<br/><br/>${link}`,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
async sendPasswordResetEmail({ email, url, name }: PasswordResetEmailData) {
|
||||
const link = `<a href="${url}" style="display:inline-block;background:#1e90ff;color:#fff;text-decoration:none;padding:12px 24px;border-radius:12px;font-weight:600;">Restablecer contraseña</a>`
|
||||
await this.send(
|
||||
email,
|
||||
'Restablece tu contraseña en Gruperly',
|
||||
this.layout(
|
||||
'Solicitaste restablecer tu contraseña',
|
||||
`${name ? `Hola ${name}, ` : 'Hola, '}haz clic en el botón para elegir una nueva contraseña (el enlace vence en 1 hora). Si no fuiste tú, ignora este email.<br/><br/>${link}`,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
async sendOrganizationInvitation({ email, url, organizationName }: InvitationEmailData) {
|
||||
const link = `<a href="${url}" style="display:inline-block;background:#1e90ff;color:#fff;text-decoration:none;padding:12px 24px;border-radius:12px;font-weight:600;">Unirme a ${organizationName}</a>`
|
||||
await this.send(
|
||||
email,
|
||||
`Te invitaron a ${organizationName} en Gruperly`,
|
||||
this.layout(
|
||||
`Te invitaron a ${organizationName}`,
|
||||
`Acepta la invitación con el botón de abajo para empezar a colaborar en Gruperly.<br/><br/>${link}`,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Futuro: proveedores transaccionales (Resend, SendGrid, Postmark).
|
||||
// Añadir implementaciones y alternar con EMAIL_PROVIDER.
|
||||
export function createEmailProvider(): EmailProvider {
|
||||
return new SMTPEmailProvider()
|
||||
}
|
||||
|
||||
export const emailProvider = createEmailProvider()
|
||||
3
apps/backend/src/lib/error-message.ts
Normal file
3
apps/backend/src/lib/error-message.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export function toErrorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
25
apps/backend/src/lib/pagination.ts
Normal file
25
apps/backend/src/lib/pagination.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
type PaginationInput = {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
};
|
||||
|
||||
type PaginationMetadata = PaginationInput & {
|
||||
total: number;
|
||||
totalPages: number;
|
||||
};
|
||||
|
||||
export function getPaginationMetadata(
|
||||
{ page, pageSize }: PaginationInput,
|
||||
total: number,
|
||||
): PaginationMetadata {
|
||||
return {
|
||||
page,
|
||||
pageSize,
|
||||
total,
|
||||
totalPages: Math.ceil(total / pageSize),
|
||||
};
|
||||
}
|
||||
|
||||
export function getPaginationOffset({ page, pageSize }: PaginationInput): number {
|
||||
return (page - 1) * pageSize;
|
||||
}
|
||||
72
apps/backend/src/lib/prisma.ts
Normal file
72
apps/backend/src/lib/prisma.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import 'dotenv/config';
|
||||
import { type Prisma, PrismaClient } from '@generated/prisma/client';
|
||||
import type { Result } from '@gruperly/shared';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
|
||||
let prismaClient: PrismaClient | undefined;
|
||||
|
||||
function createPrismaClient(): PrismaClient {
|
||||
const databaseUrl = process.env.DATABASE_URL;
|
||||
if (!databaseUrl) {
|
||||
throw new Error('DATABASE_URL environment variable is required');
|
||||
}
|
||||
|
||||
return new PrismaClient({
|
||||
adapter: new PrismaPg({ connectionString: databaseUrl }),
|
||||
});
|
||||
}
|
||||
|
||||
export function getPrismaClient(): PrismaClient {
|
||||
prismaClient ??= createPrismaClient();
|
||||
return prismaClient;
|
||||
}
|
||||
|
||||
const prisma = new Proxy({} as PrismaClient, {
|
||||
get(_target, property) {
|
||||
const client = getPrismaClient();
|
||||
const value = Reflect.get(client, property);
|
||||
return typeof value === 'function' ? value.bind(client) : value;
|
||||
},
|
||||
});
|
||||
|
||||
export default prisma;
|
||||
|
||||
export type PrismaTransaction = Prisma.TransactionClient;
|
||||
|
||||
export type PrismaDb = PrismaClient | PrismaTransaction;
|
||||
|
||||
class ResultRollbackError<TError> extends Error {
|
||||
constructor(readonly result: Result<never, TError>) {
|
||||
super('Transaction rolled back because callback returned Result.err');
|
||||
}
|
||||
}
|
||||
|
||||
export class UnitOfWork {
|
||||
constructor(private readonly prisma: PrismaClient) {}
|
||||
|
||||
async execute<T>(callback: (tx: PrismaTransaction) => Promise<T>): Promise<T> {
|
||||
return this.prisma.$transaction(callback);
|
||||
}
|
||||
|
||||
async executeResult<TValue, TError>(
|
||||
callback: (tx: PrismaTransaction) => Promise<Result<TValue, TError>>,
|
||||
options?: { isolationLevel?: Prisma.TransactionIsolationLevel },
|
||||
): Promise<Result<TValue, TError>> {
|
||||
try {
|
||||
return await this.prisma.$transaction(async (tx) => {
|
||||
const result = await callback(tx);
|
||||
if (!result.ok) {
|
||||
throw new ResultRollbackError(result);
|
||||
}
|
||||
|
||||
return result;
|
||||
}, options);
|
||||
} catch (error) {
|
||||
if (error instanceof ResultRollbackError) {
|
||||
return error.result;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user