Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[signup/be] baseresponse를 위한 interceptor 구현 #47

Merged
merged 2 commits into from
Nov 16, 2023
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
7 changes: 7 additions & 0 deletions be/src/baseresponse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export class BaseResponse<T> {
constructor(
public data: T,
public message: string,
public statusCode: number
) {}
}
21 changes: 21 additions & 0 deletions be/src/error.filter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import {
ArgumentsHost,
Catch,
ExceptionFilter,
HttpException,
} from "@nestjs/common";
import { BaseResponse } from "./baseResponse";
import { Response } from "express";

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const status = exception.getStatus();

response
.status(status)
.json(new BaseResponse(null, exception.message, status));
}
}
5 changes: 4 additions & 1 deletion be/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { NestFactory } from "@nestjs/core";
import { SwaggerModule, DocumentBuilder } from "@nestjs/swagger";
import { AppModule } from "./app.module";
import { TransformInterceptor } from "./response.interceptor";
import { HttpExceptionFilter } from "./error.filter";

async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix("api");
app.useGlobalFilters(new HttpExceptionFilter());
app.useGlobalInterceptors(new TransformInterceptor());

const config = new DocumentBuilder()
.setTitle("Example API")
Expand All @@ -14,7 +18,6 @@ async function bootstrap() {
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup("api", app, document);

await app.listen(3000);
}
bootstrap();
25 changes: 25 additions & 0 deletions be/src/response.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
} from "@nestjs/common";
import { Observable } from "rxjs";
import { map } from "rxjs/operators";
import { BaseResponse } from "./baseResponse";

@Injectable()
export class TransformInterceptor<T>
implements NestInterceptor<T, BaseResponse<T>>
{
intercept(
context: ExecutionContext,
next: CallHandler<T>
): Observable<BaseResponse<T>> {
return next
.handle()
.pipe(
map((data) => ({ data: data, message: "Success", statusCode: 200 }))
);
}
}
81 changes: 40 additions & 41 deletions be/src/user/entities/user.entity.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,41 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
DeleteDateColumn
} from 'typeorm';

@Entity()
export class User {
@PrimaryGeneratedColumn('increment')
id: number;

@Column({ type: 'varchar', length: 20, unique : true })
nickName: string;

@Column({ type: 'varchar', length: 50 })
email: string;

@Column({ type: 'int' })
age: number;

@Column({ type: 'boolean' })
gender: boolean;

@Column({ type: 'varchar', length: 50, nullable: true })
password: string | null;

@Column({ type: 'varchar', length: 20, nullable: true })
social_provider: string | null;

@CreateDateColumn({ type: 'timestamp' })
created_at: Date;

@DeleteDateColumn({ type: 'timestamp', nullable: true})
deleted_at: Date | null;

@UpdateDateColumn({ type: 'timestamp'})
updated_at: Date;
}

Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
DeleteDateColumn,
} from "typeorm";

@Entity()
export class User {
@PrimaryGeneratedColumn("increment")
id: number;

@Column({ type: "varchar", length: 20, unique: true })
nickName: string;

@Column({ type: "varchar", length: 50 })
email: string;

@Column({ type: "int" })
age: number;

@Column({ type: "boolean" })
gender: boolean;

@Column({ type: "varchar", length: 50, nullable: true })
password: string | null;

@Column({ type: "varchar", length: 20, nullable: true })
social_provider: string | null;

@CreateDateColumn({ type: "timestamp" })
created_at: Date;

@DeleteDateColumn({ type: "timestamp", nullable: true })
deleted_at: Date | null;

@UpdateDateColumn({ type: "timestamp" })
updated_at: Date;
}
6 changes: 3 additions & 3 deletions be/src/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,17 @@ import {
UsePipes,
ValidationPipe,
} from "@nestjs/common";
import { ApiBody, ApiOperation, ApiResponse } from "@nestjs/swagger";
import { ApiOperation, ApiResponse } from "@nestjs/swagger";
import { UserInfoDto } from "./dto/userInfo.dto";
import { UserService } from "./user.service";

@Controller("user")
export class UserController {
constructor(private userService: UserService) { }
constructor(private userService: UserService) {}

@Post()
@ApiOperation({ summary: "유저 회원가입" })
@ApiResponse({ status: 200, description: "회원가입 성공", type: UserInfoDto })
@ApiResponse({ status: 200, description: "회원가입 성공" })
@ApiResponse({ status: 400, description: "부적절한 요청" })
@UsePipes(new ValidationPipe())
singup(@Body() userInfoDto: UserInfoDto) {
Expand Down
13 changes: 6 additions & 7 deletions be/src/user/user.repository.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { DataSource, Repository } from 'typeorm';
import { User } from './entities/user.entity';
import { UserInfoDto } from './dto/userInfo.dto';
import { ConflictException, Injectable } from '@nestjs/common';
import { DataSource, Repository } from "typeorm";
import { User } from "./entities/user.entity";
import { UserInfoDto } from "./dto/userInfo.dto";
import { ConflictException, Injectable } from "@nestjs/common";

@Injectable()
export class UserRepository extends Repository<User> {
Expand All @@ -12,12 +12,11 @@ export class UserRepository extends Repository<User> {
const newUser = this.create(userinfoDto);
try {
await this.save(newUser);
}
catch (err) {
} catch (err) {
if (err.code === "23505") {
throw new ConflictException("Duplicated Value");
}
}
return;
}
}
}
18 changes: 8 additions & 10 deletions be/src/user/user.service.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
import { Injectable } from "@nestjs/common";
import { UserInfoDto } from "./dto/userInfo.dto";
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './entities/user.entity';
import { InjectRepository } from "@nestjs/typeorm";
import { UserRepository } from "./user.repository";

@Injectable()
export class UserService {
constructor(
@InjectRepository(UserRepository)
private usersRepository: UserRepository,
) { }
signup(userInfoDto: UserInfoDto) {
return this.usersRepository.createUser(userInfoDto);
}
constructor(
@InjectRepository(UserRepository)
private usersRepository: UserRepository
) {}
signup(userInfoDto: UserInfoDto) {
return this.usersRepository.createUser(userInfoDto);
}
}