Skip to content

Commit

Permalink
Merge pull request #169 from LocalMingle/dev
Browse files Browse the repository at this point in the history
[작업완료]: events, search, data 테스트 코드 작성
  • Loading branch information
kimjonghwa230412 authored Nov 13, 2023
2 parents 2aeba19 + 953b675 commit 3c8341d
Show file tree
Hide file tree
Showing 15 changed files with 249 additions and 104 deletions.
9 changes: 4 additions & 5 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,14 +93,13 @@ export class AuthController {
this.authService.OAuthLogin({ req, res });
}
//-----------------------구글 로그인-----------------------------//
@Get('/login/google') //restAPI만들기. 엔드포인트는 users/login/google.
@Get('/login/google')
@ApiOperation({ summary: '구글 소셜 로그인' })
@UseGuards(AuthGuard('google')) //인증과정을 거쳐야하기때문에 UseGuards를 써주고 passport인증으로 AuthGuard를 써준다. 이름은 google로
@UseGuards(AuthGuard('google'))
async loginGoogle(
@Req() req: Request & IOAuthUser,
@Res() res: Response //Nest.js가 express를 기반으로 하기때문에 Request는 express에서 import한다.
@Req() req: Request & IOAuthUser, //
@Res() res: Response
) {
//프로필을 받아온 다음, 로그인 처리해야하는 곳(auth.service.ts에서 선언해준다)
this.authService.OAuthLogin({ req, res });
}

Expand Down
1 change: 0 additions & 1 deletion src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ export const jwtSecret = process.env.JWT_SECRET;
imports: [PrismaModule, PassportModule, UsersModule, JwtModule.register({})],
controllers: [AuthController],
providers: [
AuthService,
AuthService,
UsersService,
JwtAccessStrategy,
Expand Down
6 changes: 2 additions & 4 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ export class AuthService {
) {}

async login({ email, password, res }: IAuthServiceLogin): Promise<{
// 리팩토링 시 res 빼도 작동하는지 테스트
accessToken: string;
refreshToken: string;
userId: number;
Expand Down Expand Up @@ -76,7 +75,7 @@ export class AuthService {
return refreshToken;
}

async refreshAccessToken(refreshToken: string): Promise<string> {
refreshAccessToken(refreshToken: string): string {
// 리프레시 토큰의 유효성을 검증
const decodedToken = this.jwtService.verify(refreshToken, {
secret: process.env.JWT_REFRESH_KEY,
Expand All @@ -85,7 +84,7 @@ export class AuthService {
// 리프레시 토큰이 유효하다면 새로운 액세스 토큰을 발급
const userId = decodedToken.sub; // 추출된 사용자 ID

const newAccessToken = await this.getAccessToken({
const newAccessToken = this.getAccessToken({
user: { userId }, // 사용자 ID를 전달
});
return newAccessToken;
Expand Down Expand Up @@ -114,7 +113,6 @@ export class AuthService {

// 2-1. 사용자가 삭제되지 않았는지 확인 (deletedAt가 null이어야 함)
if (user.deletedAt !== null) {
// res.redirect('http://localhost:5000/');
throw new UnauthorizedException('사용자가 삭제되었습니다.');
}

Expand Down
18 changes: 0 additions & 18 deletions src/chats/chats.gateway.spec.ts

This file was deleted.

16 changes: 7 additions & 9 deletions src/chats/chats.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,21 +58,20 @@ export class ChatsGateway
});
}
// WebSocketGateway가 초기화될 때 실행되는 메소드
// WebSocketGateway가 초기화되면 로그를 출력합니다.
afterInit() {
this.logger.log('init');
}

async handleDisconnect(@ConnectedSocket() socket: Socket) {
const user = await this.socketModel.findOne({ socketId: socket.id });
console.log('연결해제 유저 확인', user);
console.log('연결해제 소켓 아이디', socket.id);
// console.log('연결해제 유저 확인', user);
// console.log('연결해제 소켓 아이디', socket.id);
if (user) {
socket.broadcast.emit('disconnect_user', user);
await user.deleteOne();
// 유저 리스트에서 해당 유저 삭제
this.userList = this.userList.filter((u) => u.userId !== user.userId); // 수정된 부분
console.log('연결 해제 유저리스트 ', this.userList);
// console.log('연결 해제 유저리스트 ', this.userList);
socket.broadcast.emit('userList', this.userList);
}
this.logger.log(
Expand All @@ -81,10 +80,11 @@ export class ChatsGateway
}

// 클라이언트가 연결되면 해당 클라이언트의 ID와 네임스페이스 정보를 로그에 출력
async handleConnection(@ConnectedSocket() socket: Socket) {
handleConnection(@ConnectedSocket() socket: Socket) {
this.logger.log(`connected : ${socket.id} ${socket.nsp.name}`);
// await this.logger.log(`connected : ${socket.id} ${socket.nsp.name}`);
}

//채팅방 접속시
@SubscribeMessage('join_room')
async handleJoinRoom(
@MessageBody()
Expand Down Expand Up @@ -129,7 +129,7 @@ export class ChatsGateway
socket.emit('chat_history', chatHistory);
// 방에 있는 모든 사용자에게 userList 전송
this.server.to(String(payload.roomId)).emit('user_connected', payload);
console.log('유저리스트 콘솔', this.userList);
// console.log('유저리스트 콘솔', this.userList);
this.server.to(String(payload.roomId)).emit('userList', this.userList);
}
}
Expand Down Expand Up @@ -168,11 +168,9 @@ export class ChatsGateway
profileImg: profileImg,
},
];
// const userList = await this.socketModel.find({ nickname: { $in: [nickname] } });
// MongoDB에 채팅 메시지 저장
await this.chattingModel.create({
userList: userList,
// user: socketObj,
nickname: messageData.nickname,
profileImg: messageData.profileImg,
roomId: messageData.roomId,
Expand Down
12 changes: 0 additions & 12 deletions src/chats/models/chattings.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,6 @@ const options: SchemaOptions = {
};
@Schema(options)
export class Chatting extends Document {
// @Prop({
// type: {
// _id: { type: Types.ObjectId, required: true, ref: 'sockets' },
// id: { type: String },
// nickname: { type: String, required: true },
// profileImg: { type: String }, // 추가: 프로필 이미지
// roomId: { type: Number }, // 추가: 방 ID 또는 방 식별자
// time: { type: Date },
// },
// })
// @IsNotEmpty()
// userList: SocketModel;
@Prop({
ref: 'Event',
})
Expand Down
50 changes: 46 additions & 4 deletions src/data/data.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,62 @@
import { Test, TestingModule } from '@nestjs/testing';
import { DataController } from './data.controller';
import { DataService } from './data.service';
import { DataController } from './data.controller';
import { PrismaModule } from 'src/prisma/prisma.module';

describe('DataController', () => {
describe('CityController', () => {
let controller: DataController;
let dataService: DataService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [DataController],
providers: [DataService],
imports: [PrismaModule]
}).compile();

controller = module.get<DataController>(DataController);
dataService = module.get<DataService>(DataService);
});

it('should be defined', () => {
expect(controller).toBeDefined();
describe('cityData', () => {
it('should return city data for a valid language', async () => {
const mockQuery = { lang: 'en' };

const mockCityData = {
lang: 'en',
items: [
{ doName: 'City / Province'},
{ doName: 'Seoul' },
{ doName: 'Busan' },
{ doName: 'Daegu' },
{ doName: 'Incheon' },
{ doName: 'Gwangju' },
{ doName: 'Daejeon' },
{ doName: 'Ulsan' },
{ doName: 'Sejong' },
{ doName: 'Gyeonggi-do' },
{ doName: 'Gangwon-do' },
{ doName: 'Chungcheongbuk-do' },
{ doName: 'Chungcheongnam-do' },
{ doName: 'Jeollabuk-do' },
{ doName: 'Jeollanam-do' },
{ doName: 'Gyeongsangbuk-do' },
{ doName: 'Gyeongsangnam-do' },
{ doName: 'Jeju-do' },
],
}

const result = await controller.cityData(mockQuery);

expect(result).toEqual(mockCityData);
});

it('should return an error message for an invalid language', async () => {
const mockQuery = { lang: 'fr' };

const result = await controller.cityData(mockQuery);

expect(result).toEqual({ message: '[ko, en, jp] 중 하나를 입력하세요' });
});
});
});
2 changes: 1 addition & 1 deletion src/data/data.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ import { DataController } from './data.controller';
@Module({
controllers: [DataController],
providers: [DataService],
imports: [PrismaModule]
imports: [PrismaModule],
})
export class DataModule {}
25 changes: 16 additions & 9 deletions src/data/data.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
import { Test, TestingModule } from '@nestjs/testing';
import { DataService } from './data.service';

describe('DataService', () => {
let service: DataService;
let dataService;
let mockPrisma;

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

service = module.get<DataService>(DataService);
mockPrisma = {
region: {
findMany: jest.fn(),
},
};
dataService = new DataService(mockPrisma);
});

it('should be defined', () => {
expect(service).toBeDefined();
test('guNameData Method', async () => {
const query = { doName: 'exampleDoName' };
await dataService.guNameData(query);

expect(mockPrisma.region.findMany).toHaveBeenCalledWith({
where: { doName: query.doName },
select: { guName: true },
});
});
});
10 changes: 5 additions & 5 deletions src/data/interface/city.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ export const city = [
{
lang: 'ko',
items: [
{ doName: '시 / 도'},
{ doName: '시 / 도' },
{ doName: '서울특별시' },
{ doName: '부산광역시' },
{ doName: '대구광역시' },
Expand All @@ -25,7 +25,7 @@ export const city = [
{
lang: 'jp',
items: [
{ doName: "市 / 道"},
{ doName: '市 / 道' },
{ doName: 'ソウル特別市' },
{ doName: '釜山広域市' },
{ doName: '大邱広域市' },
Expand All @@ -48,7 +48,7 @@ export const city = [
{
lang: 'en',
items: [
{ doName: 'City / Province'},
{ doName: 'City / Province' },
{ doName: 'Seoul' },
{ doName: 'Busan' },
{ doName: 'Daegu' },
Expand All @@ -71,6 +71,6 @@ export const city = [
];

export const filter = {
category: ['선택','☕맛집/커피', '🏃‍♂️운동/건강', '🐾애완동물', '📕공부/교육'],
verify: ['선택','🙋‍♀️아무나', '🏡동네만'],
category: ['선택', '☕맛집/커피', '🏃‍♂️운동/건강', '🐾애완동물', '📕공부/교육'],
verify: ['선택', '🙋‍♀️아무나', '🏡동네만'],
};
2 changes: 1 addition & 1 deletion src/events/dto/create-event.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
Max,
} from 'class-validator';

export class CreateEventDto {
export class CreateEventDto {
@IsString()
@IsNotEmpty()
@ApiProperty({
Expand Down
Loading

0 comments on commit 3c8341d

Please sign in to comment.