Skip to content

Commit

Permalink
Feat/get chat list improve (#64)
Browse files Browse the repository at this point in the history
* ismymsg 추가

* 채팅 가져오기 학생 오류 수정

* dynamoDB 채팅 메시지 적재 로직 수정.

* 메시지 보내는 과정 분기

* cherry pick 메시지 보내는 과정 분기

* offer service 채팅 보내기 프로토콜 변경

* offer service 채팅 보내기 프로토콜 변경

* offer service 채팅 보내기 프로토콜 변경

* offer service 채팅 보내기 프로토콜 변경

* offer service 채팅 보내기 프로토콜 변경

* offer service 채팅 보내기 프로토콜 변경

* console.log 추가

* console.log 추가

* console.log 추가

* console.log 추가

* console.log 추가

* console.log 추가

* chatting findOne 추가
  • Loading branch information
seongyunlee authored Sep 27, 2023
1 parent 336dc02 commit 9d72a54
Show file tree
Hide file tree
Showing 11 changed files with 199 additions and 134 deletions.
31 changes: 2 additions & 29 deletions src/chatting/chatting.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { AccessToken } from '../auth/entities/auth.entity';
import { ChattingService } from './chatting.service';
import { ChattingOperation } from './description/chatting.operation';
import { ChattingResponse } from './description/chatting.response';
import { CreateChattingDto } from './dto/create-chatting.dto';
import { UpdateChattingDto } from './dto/update-chatting.dto';
import {
Body,
Expand All @@ -12,7 +11,6 @@ import {
Headers,
Param,
Patch,
Post,
} from '@nestjs/common';
import {
ApiBearerAuth,
Expand All @@ -34,39 +32,14 @@ export class ChattingController {
return this.chattingService.getChatList(AccessToken.userId(headers));
}

@Post()
create(
@Headers() headers: Headers,
@Body() createChattingDto: CreateChattingDto,
) {
/*
return this.chattingService.create(
AccessToken.userId(headers),
createChattingDto,
);*/
}

/*
@Post('send')
sendMessage(
@Headers() headers: Headers,
@Body() sendMessageDto: SendMessageDto,
) {
return this.chattingService.sendMessage(
AccessToken.userId(headers),
sendMessageDto,
);
}
*/

@Get()
findAll() {
return this.chattingService.findAll();
}

@Get(':chattingRoomId')
findOne(@Param('chattingRoomId') id: string) {
return this.chattingService.findOne(id);
findOne(@Param('chattingRoomId') id: string, @Headers() headers: Headers) {
return this.chattingService.findOne(id, AccessToken.userId(headers));
}

@Patch(':id')
Expand Down
4 changes: 2 additions & 2 deletions src/chatting/chatting.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,12 @@ export class ChattingRepository {
roomId: string,
senderId: string,
format: string,
message?: any,
body?: any,
) {
const newMessage = {
sender: senderId,
format: format,
body: JSON.stringify(message),
body: JSON.stringify(body),
createdAt: new Date().toISOString(),
};
return await this.chattingModel.update(
Expand Down
93 changes: 35 additions & 58 deletions src/chatting/chatting.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
NestedChatRoomInfo,
} from './items/chat.list';
import { Injectable } from '@nestjs/common';
import { v4 as uuid } from 'uuid';

@Injectable()
export class ChattingService {
Expand All @@ -24,6 +25,8 @@ export class ChattingService {
try {
const userInfo = await this.userRepository.get(userId);

const insertedQuestions = new Set<string>();

const chatRooms: ChatRoom[] = await Promise.all(
//Join Chatting & Question
userInfo.participatingChattingRooms.map(async (roomId) => {
Expand All @@ -37,70 +40,31 @@ export class ChattingService {
}),
);

const chatLists = this.groupChatRoomByState(chatRooms);
if (userInfo.role == 'student') {
const questions =
await this.questionRepository.getStudentPendingQuestions(userId);
const questionIds = [];
for (let i = 0; i < questions.count; i++) {
questionIds.push(questions[i].id);
if (insertedQuestions.has(questions[i].id)) continue;
const question = questions[i];
const questionRoom: ChatRoom = {
id: uuid(),
roomImage: question.problem.mainImage,
title: question.problem.description,
questionInfo: question,
status: ChattingStatus.pending,
isSelect: false,
questionId: question.id,
};
chatRooms.push(questionRoom);
}
chatLists.normalProposed = await this.groupNormalProposedForStudent(
chatLists.normalProposed,
questionIds,
);
}

return new Success('채팅방 목록을 불러왔습니다.', chatLists);
return new Success('채팅방 목록을 불러왔습니다.', chatRooms);
} catch (error) {
return new Fail(error.message);
}
}

async groupNormalProposedForStudent(
chatRooms: ChatRoom[],
pendingQuestionIds: string[],
): Promise<ChatRoom[]> {
const result = {};
chatRooms.forEach((chatRoom) => {
if (chatRoom.questionId in result) {
result[chatRoom.questionId].teachers.push(chatRoom);
} else {
const questionRoom: ChatRoom = {
teachers: [chatRoom],
isTeacherRoom: false,
roomImage: chatRoom.problemImage,
title: chatRoom.questionInfo.problem.description,
schoolSubject: chatRoom.schoolSubject,
schoolLevel: chatRoom.schoolLevel,
status: ChattingStatus.pending,
questionId: chatRoom.questionId,
problemImage: chatRoom.problemImage,
isSelect: false,
};
result[chatRoom.questionId] = questionRoom;
}
});

for (const questionId of pendingQuestionIds) {
if (!(questionId in result)) {
const questionInfo = await this.questionRepository.getInfo(questionId);
result[questionId] = {
teachers: [],
isTeacherRoom: false,
roomImage: questionInfo.problem.mainImage,
title: questionInfo.problem.description,
isSelect: false,
status: ChattingStatus.pending,
questionId: questionId,
problemImage: questionInfo.problem.mainImage,
};
}
}

return Object.values(result);
}

groupChatRoomByState(chatRooms: ChatRoom[]): ChatList {
const result: ChatList = {
normalProposed: [],
Expand Down Expand Up @@ -175,12 +139,8 @@ export class ChattingService {
status: status,
roomImage: opponentInfo.profileImage,
questionId: questionInfo.id,
schoolSubject: questionInfo.problem.schoolSubject,
schoolLevel: questionInfo.problem.schoolLevel,
problemImage: questionInfo.problem.mainImage,
isSelect: questionInfo.isSelect,
opponentId: opponentInfo?.id,
isTeacherRoom: true,
questionInfo: questionInfo,
title: opponentInfo?.name,
};
Expand Down Expand Up @@ -231,8 +191,25 @@ export class ChattingService {
return await this.chattingRepository.findAll();
}

async findOne(chattingRoomId: string) {
return await this.chattingRepository.findOne(chattingRoomId);
async findOne(chattingRoomId: string, userId: string) {
try {
const room = await this.chattingRepository.findOne(chattingRoomId);
if (room.studentId == userId || room.teacherId == userId) {
const userInfo = await this.userRepository.get(userId);
const questionInfo = await this.questionRepository.getInfo(
room.questionId,
);
const roomInfo = await this.makeChatItem(
{ roomInfo: room, questionInfo },
userInfo,
);
return new Success('채팅방 정보를 불러왔습니다.', roomInfo);
} else {
return new Fail('해당 채팅방에 대한 권한이 없습니다.');
}
} catch (error) {
return new Fail('해당 채팅방 정보가 없습니다.');
}
}

update(id: number, updateChattingDto: UpdateChattingDto) {
Expand Down
5 changes: 0 additions & 5 deletions src/chatting/items/chat.list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,9 @@ export interface ChatRoom {
id?: string;
title: string;
roomImage: string;
problemImage?: string;
opponentId?: string;
schoolSubject: string;
schoolLevel: string;
isSelect: boolean;
isTeacherRoom: boolean;
questionInfo?: Question;
teachers?: ChatRoom[];
questionId: string;
}

Expand Down
3 changes: 2 additions & 1 deletion src/offer/offer.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { AgoraModule } from '../agora/agora.module';
import { ChattingRepository } from '../chatting/chatting.repository';
import { dynamooseModule } from '../config.dynamoose';
import { QuestionRepository } from '../question/question.repository';
import { SocketModule } from '../socket/socket.module';
import { TutoringRepository } from '../tutoring/tutoring.repository';
import { UploadRepository } from '../upload/upload.repository';
import { UserRepository } from '../user/user.repository';
Expand All @@ -11,7 +12,7 @@ import { OfferService } from './offer.service';
import { Module } from '@nestjs/common';

@Module({
imports: [dynamooseModule, AgoraModule],
imports: [dynamooseModule, AgoraModule, SocketModule],
controllers: [OfferController],
providers: [
OfferService,
Expand Down
29 changes: 21 additions & 8 deletions src/offer/offer.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ChattingRepository } from '../chatting/chatting.repository';
import { QuestionRepository } from '../question/question.repository';
import { Fail, Success } from '../response';
import { SocketGateway } from '../socket/socket.gateway';
import { UserRepository } from '../user/user.repository';
import { OfferRepository } from './offer.repository';
import { Injectable } from '@nestjs/common';
Expand All @@ -12,6 +13,7 @@ export class OfferService {
private readonly userRepository: UserRepository,
private readonly chattingRepository: ChattingRepository,
private readonly questionRepository: QuestionRepository,
private readonly socketGateway: SocketGateway,
) {}

async append(userId: string, questionId: string) {
Expand Down Expand Up @@ -49,19 +51,29 @@ export class OfferService {
const requestMessage = {
text: '안녕하세요 선생님! 언제 수업 가능하신가요?',
};
console.log(
'chatRoomId',
chatRoomId,
'studentId',
studentId,
'userId',
userId,
);

//TODO: redis pub/sub으로 변경
await this.chattingRepository.sendMessage(
chatRoomId,
await this.socketGateway.sendMessageToBothUser(
studentId,
userId,
chatRoomId,
'problem-image',
problemMessage,
JSON.stringify(problemMessage),
);
await this.chattingRepository.sendMessage(
chatRoomId,
await this.socketGateway.sendMessageToBothUser(
studentId,
userId,
chatRoomId,
'text',
requestMessage,
JSON.stringify(requestMessage),
);

return new Success('질문 대기열에 추가되었습니다.', { chatRoomId });
Expand Down Expand Up @@ -114,9 +126,10 @@ export class OfferService {
offerTeacherId,
);
//TODO: redis pub/sub으로 변경
await this.chattingRepository.sendMessage(
teacherChatId,
await this.socketGateway.sendMessageToBothUser(
userId,
offerTeacherId,
teacherChatId,
'text',
'죄송합니다.\n다른 선생님과 수업을 진행하기로 했습니다.',
);
Expand Down
8 changes: 8 additions & 0 deletions src/question/question.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,12 @@ export class QuestionController {
list() {
return this.questionService.getPendingNormalQuestions();
}

@ApiTags('Question')
@ApiBearerAuth('Authorization')
@ApiOperation(QuestionOperation.list)
@Get('question/info/:questionId')
getQuestionInfo(@Param('questionId') questionId: string) {
return this.questionService.getQuestionInfo(questionId);
}
}
3 changes: 2 additions & 1 deletion src/question/question.module.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ChattingRepository } from '../chatting/chatting.repository';
import { dynamooseModule } from '../config.dynamoose';
import { SocketModule } from '../socket/socket.module';
import { UploadRepository } from '../upload/upload.repository';
import { UserRepository } from '../user/user.repository';
import { QuestionController } from './question.controller';
Expand All @@ -8,7 +9,7 @@ import { QuestionService } from './question.service';
import { Module } from '@nestjs/common';

@Module({
imports: [dynamooseModule],
imports: [dynamooseModule, SocketModule],
controllers: [QuestionController],
providers: [
QuestionService,
Expand Down
26 changes: 19 additions & 7 deletions src/question/question.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ChattingRepository } from '../chatting/chatting.repository';
import { Fail, Success } from '../response';
import { SocketGateway } from '../socket/socket.gateway';
import { UserRepository } from '../user/user.repository';
import {
CreateNormalQuestionDto,
Expand All @@ -16,6 +17,7 @@ export class QuestionService {
private readonly questionRepository: QuestionRepository,
private readonly chattingRepository: ChattingRepository,
private readonly userRepository: UserRepository,
private readonly socketGateway: SocketGateway,
) {}

/**
Expand Down Expand Up @@ -94,18 +96,19 @@ export class QuestionService {
startDateTime: createQuestionDto.requestTutoringStartTime,
};

//TODO: redis pub/sub으로 변경
await this.chattingRepository.sendMessage(
chatRoomId,
await this.socketGateway.sendMessageToBothUser(
userId,
teacherId,
chatRoomId,
'problem-image',
problemMessage,
JSON.stringify(problemMessage),
);
await this.chattingRepository.sendMessage(
chatRoomId,
await this.socketGateway.sendMessageToBothUser(
userId,
teacherId,
chatRoomId,
'appoint-request',
requestMessage,
JSON.stringify(requestMessage),
);

return new Success('질문이 생성되었습니다.', question);
Expand All @@ -114,6 +117,15 @@ export class QuestionService {
}
}

async getQuestionInfo(questionId: string) {
try {
const info = await this.questionRepository.getInfo(questionId);
return new Success('질문 정보를 가져왔습니다.', info);
} catch (error) {
return new Fail(error.message);
}
}

async delete(userId: string, questionId: string) {
try {
await this.questionRepository.delete(userId, questionId);
Expand Down
Loading

0 comments on commit 9d72a54

Please sign in to comment.