Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 3 additions & 11 deletions apps/api/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,12 @@
import { MentorProfilesModule } from './mentor-profiles/mentor-profiles.module';
import { SkillsModule } from './skills/skills.module';
import { UsersModule } from './users/users.module';
import { NotificationsModule } from './notifications/notifications.module';
<<<<<<< HEAD
import { SessionsModule } from './sessions/sessions.module';

Check failure on line 12 in apps/api/src/app.module.ts

View workflow job for this annotation

GitHub Actions / ci (20.x)

'SessionsModule' is defined but never used

Check failure on line 12 in apps/api/src/app.module.ts

View workflow job for this annotation

GitHub Actions / ci (18.x)

'SessionsModule' is defined but never used
=======
import { AuthModule } from './auth/auth.module';
import { VerifyModule } from './verify/verify.module';
import rateLimitConfig from './config/rate-limit.config'; // Import the rate limit config
>>>>>>> upstream/main
import { BookingsModule } from './bookings/bookings.module';
import { MentorsProfileModule } from './mentors-profile/mentors-profile.module';
import { ChatModule } from './chat/chat.module';

@Module({
imports: [
Expand All @@ -27,21 +23,17 @@
load: [rateLimitConfig], // Load the rate limit configuration
}),
DatabaseModule,
RedisModule,
RedisModule,
HealthModule,
AuthModule,
UsersModule,
NotificationsModule,
MentorProfilesModule,
SkillsModule,
ListingsModule,
<<<<<<< HEAD
SessionsModule,
=======
VerifyModule,
>>>>>>> upstream/main
BookingsModule,
MentorsProfileModule,
ChatModule,
],
controllers: [AppController],
providers: [AppService],
Expand Down
29 changes: 29 additions & 0 deletions apps/api/src/auth/guards/roles.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Request } from 'express';

interface AuthUser {
id: string;
role?: string;
roles?: string[];
}

@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}

canActivate(context: ExecutionContext): boolean {
const requiredRoles =
this.reflector.get<string[]>('roles', context.getHandler()) ?? [];

type RequestWithUser = Request & { user?: AuthUser };
const request = context.switchToHttp().getRequest<RequestWithUser>();
const user = request.user;

if (!user) return false;

const userRoles = user.roles ?? (user.role ? [user.role] : []);

return requiredRoles.some((role) => userRoles.includes(role));
}
}
9 changes: 9 additions & 0 deletions apps/api/src/auth/interfaces/auth-request.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Request } from 'express';

export interface AuthRequest extends Request {
user: {
id: string;
role: string;
roles?: string[];
};
}
50 changes: 36 additions & 14 deletions apps/api/src/bookings/booking-lifecycle.orchestrator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@ describe('BookingLifecycleOrchestrator', () => {
status: BookingStatus.ACCEPTED,
};

jest.spyOn(bookingsService, 'acceptBooking').mockResolvedValue(acceptedBooking);
jest
.spyOn(bookingsService, 'acceptBooking')
.mockResolvedValue(acceptedBooking);
jest.spyOn(sessionsService, 'createFromBooking').mockResolvedValue({
id: '550e8400-e29b-41d4-a716-446655440000',
bookingId: mockBooking.id,
Expand All @@ -85,8 +87,12 @@ describe('BookingLifecycleOrchestrator', () => {
const result = await orchestrator.acceptBooking(mockBooking.id);

expect(result.status).toBe(BookingStatus.ACCEPTED);
expect(bookingsService.acceptBooking).toHaveBeenCalledWith(mockBooking.id);
expect(sessionsService.createFromBooking).toHaveBeenCalledWith(mockBooking.id);
expect(bookingsService.acceptBooking).toHaveBeenCalledWith(
mockBooking.id,
);
expect(sessionsService.createFromBooking).toHaveBeenCalledWith(
mockBooking.id,
);
});

it('should fail if session creation fails', async () => {
Expand All @@ -95,14 +101,16 @@ describe('BookingLifecycleOrchestrator', () => {
status: BookingStatus.ACCEPTED,
};

jest.spyOn(bookingsService, 'acceptBooking').mockResolvedValue(acceptedBooking);
jest
.spyOn(bookingsService, 'acceptBooking')
.mockResolvedValue(acceptedBooking);
jest
.spyOn(sessionsService, 'createFromBooking')
.mockRejectedValue(new Error('Session creation failed'));

await expect(
orchestrator.acceptBooking(mockBooking.id),
).rejects.toThrow('Session creation failed');
await expect(orchestrator.acceptBooking(mockBooking.id)).rejects.toThrow(
'Session creation failed',
);
});
});

Expand All @@ -113,12 +121,16 @@ describe('BookingLifecycleOrchestrator', () => {
status: BookingStatus.DECLINED,
};

jest.spyOn(bookingsService, 'declineBooking').mockResolvedValue(declinedBooking);
jest
.spyOn(bookingsService, 'declineBooking')
.mockResolvedValue(declinedBooking);

const result = await orchestrator.declineBooking(mockBooking.id);

expect(result.status).toBe(BookingStatus.DECLINED);
expect(bookingsService.declineBooking).toHaveBeenCalledWith(mockBooking.id);
expect(bookingsService.declineBooking).toHaveBeenCalledWith(
mockBooking.id,
);
expect(sessionsService.createFromBooking).not.toHaveBeenCalled();
});
});
Expand All @@ -130,12 +142,16 @@ describe('BookingLifecycleOrchestrator', () => {
status: BookingStatus.CANCELLED,
};

jest.spyOn(bookingsService, 'cancelBooking').mockResolvedValue(cancelledBooking);
jest
.spyOn(bookingsService, 'cancelBooking')
.mockResolvedValue(cancelledBooking);

const result = await orchestrator.cancelBooking(mockBooking.id);

expect(result.status).toBe(BookingStatus.CANCELLED);
expect(bookingsService.cancelBooking).toHaveBeenCalledWith(mockBooking.id);
expect(bookingsService.cancelBooking).toHaveBeenCalledWith(
mockBooking.id,
);
});
});

Expand All @@ -146,7 +162,9 @@ describe('BookingLifecycleOrchestrator', () => {
status: BookingStatus.ACCEPTED,
};

jest.spyOn(bookingsService, 'acceptBooking').mockResolvedValue(acceptedBooking);
jest
.spyOn(bookingsService, 'acceptBooking')
.mockResolvedValue(acceptedBooking);
jest.spyOn(sessionsService, 'createFromBooking').mockResolvedValue({
id: '550e8400-e29b-41d4-a716-446655440000',
bookingId: mockBooking.id,
Expand All @@ -163,8 +181,12 @@ describe('BookingLifecycleOrchestrator', () => {

await orchestrator.acceptBooking(mockBooking.id);

expect(bookingsService.acceptBooking).toHaveBeenCalledWith(mockBooking.id);
expect(sessionsService.createFromBooking).toHaveBeenCalledWith(mockBooking.id);
expect(bookingsService.acceptBooking).toHaveBeenCalledWith(
mockBooking.id,
);
expect(sessionsService.createFromBooking).toHaveBeenCalledWith(
mockBooking.id,
);
});
});
});
5 changes: 4 additions & 1 deletion apps/api/src/bookings/booking-lifecycle.orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@ export class BookingLifecycleOrchestrator {
} catch (error) {
// If session creation fails, we have a data consistency issue
// Log it and re-throw so the error is visible
console.error(`Failed to create session for booking ${bookingId}:`, error);
console.error(
`Failed to create session for booking ${bookingId}:`,
error,
);
throw error;
}

Expand Down
20 changes: 20 additions & 0 deletions apps/api/src/chat/chat.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ChatController } from './chat.controller';
import { ChatService } from './chat.service';

describe('ChatController', () => {
let controller: ChatController;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [ChatController],
providers: [ChatService],
}).compile();

controller = module.get<ChatController>(ChatController);
});

it('should be defined', () => {
expect(controller).toBeDefined();
});
});
155 changes: 155 additions & 0 deletions apps/api/src/chat/chat.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
import {
Controller,
Get,
Post,
Body,
Param,
Query,
UseGuards,
Req,
ParseUUIDPipe,
} from '@nestjs/common';
import {
ApiTags,
ApiOperation,
ApiResponse,
ApiBearerAuth,
ApiParam,
} from '@nestjs/swagger';

import { ChatService } from './chat.service';
import { CreateMessageDto } from './dto/create-message.dto';
import { PaginationParamsDto } from './dto/pagination-params.dto';
import { PaginatedResponseDto } from './dto/paginated-response.dto';
import { ThreadResponseDto } from './dto/thread-response.dto';
import { MessageResponseDto } from './dto/message-response.dto';

import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../auth/guards/roles.guard';
import { Roles } from '../auth/decorators/roles.decorator';
import { UserRole } from '../users/enums/user-role.enum';
import type { AuthRequest } from '../auth/interfaces/auth-request.interface';

@ApiTags('chat')
@Controller('chat')
@UseGuards(JwtAuthGuard, RolesGuard)
@ApiBearerAuth()
export class ChatController {
constructor(private readonly chatService: ChatService) {}

@Get('threads')
@Roles(UserRole.MENTOR, UserRole.MENTEE)
@ApiOperation({
summary: 'Get user threads',
description: 'Retrieve all threads for the authenticated user',
})
@ApiResponse({
status: 200,
description: 'Threads retrieved successfully',
type: PaginatedResponseDto,
})
async getUserThreads(
@Req() req: AuthRequest,
@Query() paginationParams: PaginationParamsDto,
) {
return this.chatService.getUserThreads(req.user.id, paginationParams);
}

@Get('threads/:threadId')
@Roles(UserRole.MENTOR, UserRole.MENTEE)
@ApiOperation({
summary: 'Get thread details',
description: 'Retrieve details of a specific thread',
})
@ApiParam({
name: 'threadId',
description: 'Thread ID',
example: '123e4567-e89b-12d3-a456-426614174000',
})
@ApiResponse({
status: 200,
description: 'Thread retrieved successfully',
type: ThreadResponseDto,
})
async getThread(
@Req() req: AuthRequest,
@Param('threadId', ParseUUIDPipe) threadId: string,
) {
return this.chatService.getThread(threadId, req.user.id);
}

@Get('threads/:threadId/messages')
@Roles(UserRole.MENTOR, UserRole.MENTEE)
@ApiOperation({
summary: 'Get thread messages',
description: 'Retrieve messages from a specific thread with pagination',
})
@ApiParam({
name: 'threadId',
description: 'Thread ID',
example: '123e4567-e89b-12d3-a456-426614174000',
})
@ApiResponse({
status: 200,
description: 'Messages retrieved successfully',
type: PaginatedResponseDto,
})
async getThreadMessages(
@Req() req: AuthRequest,
@Param('threadId', ParseUUIDPipe) threadId: string,
@Query() paginationParams: PaginationParamsDto,
) {
return this.chatService.getThreadMessages(
threadId,
req.user.id,
paginationParams,
);
}

@Post('threads/:threadId/messages')
@Roles(UserRole.MENTOR, UserRole.MENTEE)
@ApiOperation({
summary: 'Send a message',
description: 'Send a message in a thread',
})
@ApiParam({
name: 'threadId',
description: 'Thread ID',
example: '123e4567-e89b-12d3-a456-426614174000',
})
@ApiResponse({
status: 201,
description: 'Message sent successfully',
type: MessageResponseDto,
})
async sendMessage(
@Req() req: AuthRequest,
@Param('threadId', ParseUUIDPipe) threadId: string,
@Body() createMessageDto: CreateMessageDto,
) {
return this.chatService.sendMessage(
threadId,
req.user.id,
createMessageDto,
);
}

@Post('threads/:threadId/read')
@Roles(UserRole.MENTOR, UserRole.MENTEE)
@ApiOperation({
summary: 'Mark thread as read',
description: 'Mark all messages in a thread as read',
})
@ApiParam({
name: 'threadId',
description: 'Thread ID',
example: '123e4567-e89b-12d3-a456-426614174000',
})
async markThreadAsRead(
@Req() req: AuthRequest,
@Param('threadId', ParseUUIDPipe) threadId: string,
) {
await this.chatService.markThreadAsRead(threadId, req.user.id);
return { message: 'Thread marked as read' };
}
}
9 changes: 9 additions & 0 deletions apps/api/src/chat/chat.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { ChatService } from './chat.service';
import { ChatController } from './chat.controller';

@Module({
controllers: [ChatController],
providers: [ChatService],
})
export class ChatModule {}
Loading
Loading