feat(#5): Implement CRUD APIs for tasks, events, and projects

Implements comprehensive CRUD APIs following TDD principles with 92.44%
test coverage (exceeds 85% requirement).

Features:
- Tasks API: Full CRUD with filtering, pagination, and subtask support
- Events API: Full CRUD with recurrence support and date filtering
- Projects API: Full CRUD with task/event association
- Authentication guards on all endpoints
- Workspace-scoped queries for multi-tenant isolation
- Activity logging for all operations (CREATED, UPDATED, DELETED, etc.)
- DTOs with class-validator validation
- Comprehensive test suite (221 tests, 44 for new APIs)

Implementation:
- Services: Business logic with Prisma ORM integration
- Controllers: RESTful endpoints with AuthGuard
- Modules: Properly registered in AppModule
- Documentation: Complete API reference in docs/4-api/4-crud-endpoints/

Test Coverage:
- Tasks: 96.1%
- Events: 89.83%
- Projects: 84.21%
- Overall: 92.44%

TDD Workflow:
1. RED: Wrote failing tests first
2. GREEN: Implemented minimal code to pass tests
3. REFACTOR: Improved code quality while maintaining coverage

Refs #5

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
Jason Woltje
2026-01-28 18:43:12 -06:00
parent 05fc1c60f4
commit 132fe6ba98
30 changed files with 3812 additions and 1 deletions

View File

@@ -0,0 +1,53 @@
import {
IsString,
IsOptional,
IsUUID,
IsDateString,
IsBoolean,
IsObject,
MinLength,
MaxLength,
} from "class-validator";
/**
* DTO for creating a new event
*/
export class CreateEventDto {
@IsString({ message: "title must be a string" })
@MinLength(1, { message: "title must not be empty" })
@MaxLength(255, { message: "title must not exceed 255 characters" })
title!: string;
@IsOptional()
@IsString({ message: "description must be a string" })
@MaxLength(10000, { message: "description must not exceed 10000 characters" })
description?: string;
@IsDateString({}, { message: "startTime must be a valid ISO 8601 date string" })
startTime!: Date;
@IsOptional()
@IsDateString({}, { message: "endTime must be a valid ISO 8601 date string" })
endTime?: Date;
@IsOptional()
@IsBoolean({ message: "allDay must be a boolean" })
allDay?: boolean;
@IsOptional()
@IsString({ message: "location must be a string" })
@MaxLength(500, { message: "location must not exceed 500 characters" })
location?: string;
@IsOptional()
@IsObject({ message: "recurrence must be an object" })
recurrence?: Record<string, unknown>;
@IsOptional()
@IsUUID("4", { message: "projectId must be a valid UUID" })
projectId?: string;
@IsOptional()
@IsObject({ message: "metadata must be an object" })
metadata?: Record<string, unknown>;
}

View File

@@ -0,0 +1,3 @@
export { CreateEventDto } from "./create-event.dto";
export { UpdateEventDto } from "./update-event.dto";
export { QueryEventsDto } from "./query-events.dto";

View File

@@ -0,0 +1,48 @@
import {
IsUUID,
IsOptional,
IsInt,
Min,
Max,
IsDateString,
IsBoolean,
} from "class-validator";
import { Type } from "class-transformer";
/**
* DTO for querying events with filters and pagination
*/
export class QueryEventsDto {
@IsUUID("4", { message: "workspaceId must be a valid UUID" })
workspaceId!: string;
@IsOptional()
@IsUUID("4", { message: "projectId must be a valid UUID" })
projectId?: string;
@IsOptional()
@IsDateString({}, { message: "startFrom must be a valid ISO 8601 date string" })
startFrom?: Date;
@IsOptional()
@IsDateString({}, { message: "startTo must be a valid ISO 8601 date string" })
startTo?: Date;
@IsOptional()
@IsBoolean({ message: "allDay must be a boolean" })
@Type(() => Boolean)
allDay?: boolean;
@IsOptional()
@Type(() => Number)
@IsInt({ message: "page must be an integer" })
@Min(1, { message: "page must be at least 1" })
page?: number;
@IsOptional()
@Type(() => Number)
@IsInt({ message: "limit must be an integer" })
@Min(1, { message: "limit must be at least 1" })
@Max(100, { message: "limit must not exceed 100" })
limit?: number;
}

View File

@@ -0,0 +1,56 @@
import {
IsString,
IsOptional,
IsUUID,
IsDateString,
IsBoolean,
IsObject,
MinLength,
MaxLength,
} from "class-validator";
/**
* DTO for updating an existing event
* All fields are optional to support partial updates
*/
export class UpdateEventDto {
@IsOptional()
@IsString({ message: "title must be a string" })
@MinLength(1, { message: "title must not be empty" })
@MaxLength(255, { message: "title must not exceed 255 characters" })
title?: string;
@IsOptional()
@IsString({ message: "description must be a string" })
@MaxLength(10000, { message: "description must not exceed 10000 characters" })
description?: string | null;
@IsOptional()
@IsDateString({}, { message: "startTime must be a valid ISO 8601 date string" })
startTime?: Date;
@IsOptional()
@IsDateString({}, { message: "endTime must be a valid ISO 8601 date string" })
endTime?: Date | null;
@IsOptional()
@IsBoolean({ message: "allDay must be a boolean" })
allDay?: boolean;
@IsOptional()
@IsString({ message: "location must be a string" })
@MaxLength(500, { message: "location must not exceed 500 characters" })
location?: string | null;
@IsOptional()
@IsObject({ message: "recurrence must be an object" })
recurrence?: Record<string, unknown> | null;
@IsOptional()
@IsUUID("4", { message: "projectId must be a valid UUID" })
projectId?: string | null;
@IsOptional()
@IsObject({ message: "metadata must be an object" })
metadata?: Record<string, unknown>;
}

View File

@@ -0,0 +1,165 @@
import { describe, it, expect, beforeEach, vi } from "vitest";
import { Test, TestingModule } from "@nestjs/testing";
import { EventsController } from "./events.controller";
import { EventsService } from "./events.service";
import { AuthGuard } from "../auth/guards/auth.guard";
import { ExecutionContext } from "@nestjs/common";
describe("EventsController", () => {
let controller: EventsController;
let service: EventsService;
const mockEventsService = {
create: vi.fn(),
findAll: vi.fn(),
findOne: vi.fn(),
update: vi.fn(),
remove: vi.fn(),
};
const mockAuthGuard = {
canActivate: vi.fn((context: ExecutionContext) => {
const request = context.switchToHttp().getRequest();
request.user = {
id: "550e8400-e29b-41d4-a716-446655440002",
workspaceId: "550e8400-e29b-41d4-a716-446655440001",
};
return true;
}),
};
const mockWorkspaceId = "550e8400-e29b-41d4-a716-446655440001";
const mockUserId = "550e8400-e29b-41d4-a716-446655440002";
const mockEventId = "550e8400-e29b-41d4-a716-446655440003";
const mockRequest = {
user: {
id: mockUserId,
workspaceId: mockWorkspaceId,
},
};
const mockEvent = {
id: mockEventId,
workspaceId: mockWorkspaceId,
title: "Test Event",
description: "Test Description",
startTime: new Date("2026-02-01T10:00:00Z"),
endTime: new Date("2026-02-01T11:00:00Z"),
allDay: false,
location: "Conference Room A",
recurrence: null,
creatorId: mockUserId,
projectId: null,
metadata: {},
createdAt: new Date(),
updatedAt: new Date(),
};
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [EventsController],
providers: [
{
provide: EventsService,
useValue: mockEventsService,
},
],
})
.overrideGuard(AuthGuard)
.useValue(mockAuthGuard)
.compile();
controller = module.get<EventsController>(EventsController);
service = module.get<EventsService>(EventsService);
vi.clearAllMocks();
});
it("should be defined", () => {
expect(controller).toBeDefined();
});
describe("create", () => {
it("should create an event", async () => {
const createDto = {
title: "New Event",
startTime: new Date("2026-02-01T10:00:00Z"),
};
mockEventsService.create.mockResolvedValue(mockEvent);
const result = await controller.create(createDto, mockRequest);
expect(result).toEqual(mockEvent);
expect(service.create).toHaveBeenCalledWith(
mockWorkspaceId,
mockUserId,
createDto
);
});
});
describe("findAll", () => {
it("should return paginated events", async () => {
const query = {
workspaceId: mockWorkspaceId,
};
const paginatedResult = {
data: [mockEvent],
meta: {
total: 1,
page: 1,
limit: 50,
totalPages: 1,
},
};
mockEventsService.findAll.mockResolvedValue(paginatedResult);
const result = await controller.findAll(query, mockRequest);
expect(result).toEqual(paginatedResult);
});
});
describe("findOne", () => {
it("should return an event by id", async () => {
mockEventsService.findOne.mockResolvedValue(mockEvent);
const result = await controller.findOne(mockEventId, mockRequest);
expect(result).toEqual(mockEvent);
});
});
describe("update", () => {
it("should update an event", async () => {
const updateDto = {
title: "Updated Event",
};
const updatedEvent = { ...mockEvent, ...updateDto };
mockEventsService.update.mockResolvedValue(updatedEvent);
const result = await controller.update(mockEventId, updateDto, mockRequest);
expect(result).toEqual(updatedEvent);
});
});
describe("remove", () => {
it("should delete an event", async () => {
mockEventsService.remove.mockResolvedValue(undefined);
await controller.remove(mockEventId, mockRequest);
expect(service.remove).toHaveBeenCalledWith(
mockEventId,
mockWorkspaceId,
mockUserId
);
});
});
});

View File

@@ -0,0 +1,100 @@
import {
Controller,
Get,
Post,
Patch,
Delete,
Body,
Param,
Query,
UseGuards,
Request,
} from "@nestjs/common";
import { EventsService } from "./events.service";
import { CreateEventDto, UpdateEventDto, QueryEventsDto } from "./dto";
import { AuthGuard } from "../auth/guards/auth.guard";
/**
* Controller for event endpoints
* All endpoints require authentication
*/
@Controller("events")
@UseGuards(AuthGuard)
export class EventsController {
constructor(private readonly eventsService: EventsService) {}
/**
* POST /api/events
* Create a new event
*/
@Post()
async create(@Body() createEventDto: CreateEventDto, @Request() req: any) {
const workspaceId = req.user?.workspaceId;
const userId = req.user?.id;
if (!workspaceId || !userId) {
throw new Error("User workspaceId or userId not found");
}
return this.eventsService.create(workspaceId, userId, createEventDto);
}
/**
* GET /api/events
* Get paginated events with optional filters
*/
@Get()
async findAll(@Query() query: QueryEventsDto, @Request() req: any) {
const workspaceId = req.user?.workspaceId || query.workspaceId;
return this.eventsService.findAll({ ...query, workspaceId });
}
/**
* GET /api/events/:id
* Get a single event by ID
*/
@Get(":id")
async findOne(@Param("id") id: string, @Request() req: any) {
const workspaceId = req.user?.workspaceId;
if (!workspaceId) {
throw new Error("User workspaceId not found");
}
return this.eventsService.findOne(id, workspaceId);
}
/**
* PATCH /api/events/:id
* Update an event
*/
@Patch(":id")
async update(
@Param("id") id: string,
@Body() updateEventDto: UpdateEventDto,
@Request() req: any
) {
const workspaceId = req.user?.workspaceId;
const userId = req.user?.id;
if (!workspaceId || !userId) {
throw new Error("User workspaceId not found");
}
return this.eventsService.update(id, workspaceId, userId, updateEventDto);
}
/**
* DELETE /api/events/:id
* Delete an event
*/
@Delete(":id")
async remove(@Param("id") id: string, @Request() req: any) {
const workspaceId = req.user?.workspaceId;
const userId = req.user?.id;
if (!workspaceId || !userId) {
throw new Error("User workspaceId not found");
}
return this.eventsService.remove(id, workspaceId, userId);
}
}

View File

@@ -0,0 +1,14 @@
import { Module } from "@nestjs/common";
import { EventsController } from "./events.controller";
import { EventsService } from "./events.service";
import { PrismaModule } from "../prisma/prisma.module";
import { ActivityModule } from "../activity/activity.module";
import { AuthModule } from "../auth/auth.module";
@Module({
imports: [PrismaModule, ActivityModule, AuthModule],
controllers: [EventsController],
providers: [EventsService],
exports: [EventsService],
})
export class EventsModule {}

View File

@@ -0,0 +1,236 @@
import { describe, it, expect, beforeEach, vi } from "vitest";
import { Test, TestingModule } from "@nestjs/testing";
import { EventsService } from "./events.service";
import { PrismaService } from "../prisma/prisma.service";
import { ActivityService } from "../activity/activity.service";
import { NotFoundException } from "@nestjs/common";
describe("EventsService", () => {
let service: EventsService;
let prisma: PrismaService;
let activityService: ActivityService;
const mockPrismaService = {
event: {
create: vi.fn(),
findMany: vi.fn(),
count: vi.fn(),
findUnique: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
},
};
const mockActivityService = {
logEventCreated: vi.fn(),
logEventUpdated: vi.fn(),
logEventDeleted: vi.fn(),
};
const mockWorkspaceId = "550e8400-e29b-41d4-a716-446655440001";
const mockUserId = "550e8400-e29b-41d4-a716-446655440002";
const mockEventId = "550e8400-e29b-41d4-a716-446655440003";
const mockEvent = {
id: mockEventId,
workspaceId: mockWorkspaceId,
title: "Test Event",
description: "Test Description",
startTime: new Date("2026-02-01T10:00:00Z"),
endTime: new Date("2026-02-01T11:00:00Z"),
allDay: false,
location: "Conference Room A",
recurrence: null,
creatorId: mockUserId,
projectId: null,
metadata: {},
createdAt: new Date(),
updatedAt: new Date(),
};
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
EventsService,
{
provide: PrismaService,
useValue: mockPrismaService,
},
{
provide: ActivityService,
useValue: mockActivityService,
},
],
}).compile();
service = module.get<EventsService>(EventsService);
prisma = module.get<PrismaService>(PrismaService);
activityService = module.get<ActivityService>(ActivityService);
vi.clearAllMocks();
});
it("should be defined", () => {
expect(service).toBeDefined();
});
describe("create", () => {
it("should create an event and log activity", async () => {
const createDto = {
title: "New Event",
description: "Event description",
startTime: new Date("2026-02-01T10:00:00Z"),
allDay: false,
};
mockPrismaService.event.create.mockResolvedValue(mockEvent);
mockActivityService.logEventCreated.mockResolvedValue({});
const result = await service.create(mockWorkspaceId, mockUserId, createDto);
expect(result).toEqual(mockEvent);
expect(prisma.event.create).toHaveBeenCalledWith({
data: {
...createDto,
workspaceId: mockWorkspaceId,
creatorId: mockUserId,
allDay: false,
metadata: {},
},
include: {
creator: {
select: { id: true, name: true, email: true },
},
project: {
select: { id: true, name: true, color: true },
},
},
});
expect(activityService.logEventCreated).toHaveBeenCalledWith(
mockWorkspaceId,
mockUserId,
mockEvent.id,
{ title: mockEvent.title }
);
});
});
describe("findAll", () => {
it("should return paginated events with default pagination", async () => {
const events = [mockEvent];
mockPrismaService.event.findMany.mockResolvedValue(events);
mockPrismaService.event.count.mockResolvedValue(1);
const result = await service.findAll({ workspaceId: mockWorkspaceId });
expect(result).toEqual({
data: events,
meta: {
total: 1,
page: 1,
limit: 50,
totalPages: 1,
},
});
});
it("should filter by date range", async () => {
const startFrom = new Date("2026-02-01");
const startTo = new Date("2026-02-28");
mockPrismaService.event.findMany.mockResolvedValue([mockEvent]);
mockPrismaService.event.count.mockResolvedValue(1);
await service.findAll({
workspaceId: mockWorkspaceId,
startFrom,
startTo,
});
expect(prisma.event.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: {
workspaceId: mockWorkspaceId,
startTime: {
gte: startFrom,
lte: startTo,
},
},
})
);
});
});
describe("findOne", () => {
it("should return an event by id", async () => {
mockPrismaService.event.findUnique.mockResolvedValue(mockEvent);
const result = await service.findOne(mockEventId, mockWorkspaceId);
expect(result).toEqual(mockEvent);
});
it("should throw NotFoundException if event not found", async () => {
mockPrismaService.event.findUnique.mockResolvedValue(null);
await expect(service.findOne(mockEventId, mockWorkspaceId)).rejects.toThrow(
NotFoundException
);
});
});
describe("update", () => {
it("should update an event and log activity", async () => {
const updateDto = {
title: "Updated Event",
location: "New Location",
};
mockPrismaService.event.findUnique.mockResolvedValue(mockEvent);
mockPrismaService.event.update.mockResolvedValue({
...mockEvent,
...updateDto,
});
mockActivityService.logEventUpdated.mockResolvedValue({});
const result = await service.update(
mockEventId,
mockWorkspaceId,
mockUserId,
updateDto
);
expect(result.title).toBe("Updated Event");
expect(activityService.logEventUpdated).toHaveBeenCalled();
});
it("should throw NotFoundException if event not found", async () => {
mockPrismaService.event.findUnique.mockResolvedValue(null);
await expect(
service.update(mockEventId, mockWorkspaceId, mockUserId, { title: "Test" })
).rejects.toThrow(NotFoundException);
});
});
describe("remove", () => {
it("should delete an event and log activity", async () => {
mockPrismaService.event.findUnique.mockResolvedValue(mockEvent);
mockPrismaService.event.delete.mockResolvedValue(mockEvent);
mockActivityService.logEventDeleted.mockResolvedValue({});
await service.remove(mockEventId, mockWorkspaceId, mockUserId);
expect(prisma.event.delete).toHaveBeenCalled();
expect(activityService.logEventDeleted).toHaveBeenCalled();
});
it("should throw NotFoundException if event not found", async () => {
mockPrismaService.event.findUnique.mockResolvedValue(null);
await expect(
service.remove(mockEventId, mockWorkspaceId, mockUserId)
).rejects.toThrow(NotFoundException);
});
});
});

View File

@@ -0,0 +1,204 @@
import { Injectable, NotFoundException } from "@nestjs/common";
import { PrismaService } from "../prisma/prisma.service";
import { ActivityService } from "../activity/activity.service";
import type { CreateEventDto, UpdateEventDto, QueryEventsDto } from "./dto";
/**
* Service for managing events
*/
@Injectable()
export class EventsService {
constructor(
private readonly prisma: PrismaService,
private readonly activityService: ActivityService
) {}
/**
* Create a new event
*/
async create(workspaceId: string, userId: string, createEventDto: CreateEventDto) {
const data: any = {
...createEventDto,
workspaceId,
creatorId: userId,
allDay: createEventDto.allDay ?? false,
metadata: createEventDto.metadata || {},
};
const event = await this.prisma.event.create({
data,
include: {
creator: {
select: { id: true, name: true, email: true },
},
project: {
select: { id: true, name: true, color: true },
},
},
});
// Log activity
await this.activityService.logEventCreated(workspaceId, userId, event.id, {
title: event.title,
});
return event;
}
/**
* Get paginated events with filters
*/
async findAll(query: QueryEventsDto) {
const page = query.page || 1;
const limit = query.limit || 50;
const skip = (page - 1) * limit;
// Build where clause
const where: any = {
workspaceId: query.workspaceId,
};
if (query.projectId) {
where.projectId = query.projectId;
}
if (query.allDay !== undefined) {
where.allDay = query.allDay;
}
if (query.startFrom || query.startTo) {
where.startTime = {};
if (query.startFrom) {
where.startTime.gte = query.startFrom;
}
if (query.startTo) {
where.startTime.lte = query.startTo;
}
}
// Execute queries in parallel
const [data, total] = await Promise.all([
this.prisma.event.findMany({
where,
include: {
creator: {
select: { id: true, name: true, email: true },
},
project: {
select: { id: true, name: true, color: true },
},
},
orderBy: {
startTime: "asc",
},
skip,
take: limit,
}),
this.prisma.event.count({ where }),
]);
return {
data,
meta: {
total,
page,
limit,
totalPages: Math.ceil(total / limit),
},
};
}
/**
* Get a single event by ID
*/
async findOne(id: string, workspaceId: string) {
const event = await this.prisma.event.findUnique({
where: {
id,
workspaceId,
},
include: {
creator: {
select: { id: true, name: true, email: true },
},
project: {
select: { id: true, name: true, color: true },
},
},
});
if (!event) {
throw new NotFoundException(`Event with ID ${id} not found`);
}
return event;
}
/**
* Update an event
*/
async update(
id: string,
workspaceId: string,
userId: string,
updateEventDto: UpdateEventDto
) {
// Verify event exists
const existingEvent = await this.prisma.event.findUnique({
where: { id, workspaceId },
});
if (!existingEvent) {
throw new NotFoundException(`Event with ID ${id} not found`);
}
const event = await this.prisma.event.update({
where: {
id,
workspaceId,
},
data: updateEventDto,
include: {
creator: {
select: { id: true, name: true, email: true },
},
project: {
select: { id: true, name: true, color: true },
},
},
});
// Log activity
await this.activityService.logEventUpdated(workspaceId, userId, id, {
changes: updateEventDto,
});
return event;
}
/**
* Delete an event
*/
async remove(id: string, workspaceId: string, userId: string) {
// Verify event exists
const event = await this.prisma.event.findUnique({
where: { id, workspaceId },
});
if (!event) {
throw new NotFoundException(`Event with ID ${id} not found`);
}
await this.prisma.event.delete({
where: {
id,
workspaceId,
},
});
// Log activity
await this.activityService.logEventDeleted(workspaceId, userId, id, {
title: event.title,
});
}
}