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:
208
apps/backend/test/groups.test.ts
Normal file
208
apps/backend/test/groups.test.ts
Normal file
@@ -0,0 +1,208 @@
|
||||
import { Hono } from 'hono';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { db } = vi.hoisted(() => {
|
||||
return {
|
||||
db: {
|
||||
group: {
|
||||
findMany: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
count: vi.fn(),
|
||||
create: vi.fn(),
|
||||
},
|
||||
groupMember: {
|
||||
create: vi.fn(),
|
||||
},
|
||||
organization: {
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
} as {
|
||||
group: {
|
||||
findMany: ReturnType<typeof vi.fn>;
|
||||
findFirst: ReturnType<typeof vi.fn>;
|
||||
count: ReturnType<typeof vi.fn>;
|
||||
create: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
groupMember: { create: ReturnType<typeof vi.fn> };
|
||||
organization: { findUnique: ReturnType<typeof vi.fn> };
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('@/lib/prisma', () => ({
|
||||
default: db,
|
||||
getPrismaClient: vi.fn(),
|
||||
UnitOfWork: class {
|
||||
executeResult = vi.fn(
|
||||
async (cb: (tx: unknown) => Promise<unknown>) => cb(db),
|
||||
);
|
||||
execute = vi.fn(
|
||||
async (cb: (tx: unknown) => Promise<unknown>) => cb(db),
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
import prisma from '@/lib/prisma';
|
||||
import { groupsRoutes } from '@/modules/groups';
|
||||
|
||||
const userId = 'user-1';
|
||||
const group = {
|
||||
id: 'group-1',
|
||||
name: 'Cuadrilla Alfa',
|
||||
description: null,
|
||||
createdById: userId,
|
||||
createdAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
};
|
||||
|
||||
function makeApp(userValue: unknown) {
|
||||
const app = new Hono();
|
||||
app.use('*', async (c, next) => {
|
||||
c.set('user', userValue as never);
|
||||
await next();
|
||||
});
|
||||
app.route('/groups', groupsRoutes);
|
||||
return app;
|
||||
}
|
||||
|
||||
describe('groups routes', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('lists groups scoped to the current user', async () => {
|
||||
vi.mocked(prisma.group.findMany).mockResolvedValue([group]);
|
||||
vi.mocked(prisma.group.count).mockResolvedValue(1);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/groups');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({
|
||||
data: [
|
||||
{
|
||||
...group,
|
||||
createdAt: group.createdAt.toISOString(),
|
||||
updatedAt: group.updatedAt.toISOString(),
|
||||
},
|
||||
],
|
||||
pagination: { page: 1, pageSize: 10, total: 1, totalPages: 1 },
|
||||
});
|
||||
const where = {
|
||||
OR: [{ createdById: userId }, { members: { some: { userId } } }],
|
||||
};
|
||||
expect(prisma.group.findMany).toHaveBeenCalledWith({
|
||||
where,
|
||||
skip: 0,
|
||||
take: 10,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
expect(prisma.group.count).toHaveBeenCalledWith({ where });
|
||||
});
|
||||
|
||||
it('rejects listing groups without a session', async () => {
|
||||
const res = await makeApp(null).request('/groups');
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(await res.json()).toMatchObject({ code: 'unauthorized' });
|
||||
});
|
||||
|
||||
it('rejects invalid pagination query parameters', async () => {
|
||||
const res = await makeApp({ id: userId }).request('/groups?pageSize=101');
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('creates a group from an owned organization', async () => {
|
||||
const organization = {
|
||||
id: 'org-1',
|
||||
name: 'Escuela Alfa',
|
||||
members: [{ userId, role: 'owner' }],
|
||||
};
|
||||
vi.mocked(prisma.organization.findUnique).mockResolvedValue(organization as never);
|
||||
vi.mocked(prisma.group.findFirst).mockResolvedValue(null);
|
||||
vi.mocked(prisma.group.create).mockResolvedValue(group);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/groups/from-organization', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ organizationId: 'org-1' }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
expect(await res.json()).toEqual({
|
||||
group: {
|
||||
...group,
|
||||
createdAt: group.createdAt.toISOString(),
|
||||
updatedAt: group.updatedAt.toISOString(),
|
||||
},
|
||||
alreadyExists: false,
|
||||
});
|
||||
expect(prisma.group.create).toHaveBeenCalledWith({
|
||||
data: { name: 'Escuela Alfa', createdById: userId },
|
||||
});
|
||||
});
|
||||
|
||||
it('reuses an existing group with the same name', async () => {
|
||||
const organization = {
|
||||
id: 'org-1',
|
||||
name: 'Escuela Alfa',
|
||||
members: [{ userId, role: 'owner' }],
|
||||
};
|
||||
vi.mocked(prisma.organization.findUnique).mockResolvedValue(organization as never);
|
||||
vi.mocked(prisma.group.findFirst).mockResolvedValue(group);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/groups/from-organization', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ organizationId: 'org-1' }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.alreadyExists).toBe(true);
|
||||
expect(prisma.group.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects creating a group for an unknown organization', async () => {
|
||||
vi.mocked(prisma.organization.findUnique).mockResolvedValue(null);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/groups/from-organization', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ organizationId: 'missing' }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
expect(await res.json()).toMatchObject({ code: 'organization_not_found' });
|
||||
expect(prisma.group.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects creating a group when the user is not the owner', async () => {
|
||||
const organization = {
|
||||
id: 'org-1',
|
||||
name: 'Escuela Alfa',
|
||||
members: [{ userId: 'other-user', role: 'owner' }],
|
||||
};
|
||||
vi.mocked(prisma.organization.findUnique).mockResolvedValue(organization as never);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/groups/from-organization', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ organizationId: 'org-1' }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(await res.json()).toMatchObject({ code: 'group_owner_required' });
|
||||
expect(prisma.group.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects creating a group without a session', async () => {
|
||||
const res = await makeApp(null).request('/groups/from-organization', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ organizationId: 'org-1' }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user