DTO (Data Transfer Object) 는 데이터 전송 객체로, 데이터베이스와 애플리케이션 간에 데이터를 전송하기 위해 사용되는 객체이다. DTO는 주로 네트워크를 통해 데이터를 전송할 때 사용되며, 데티어의 구조를 정의한다.
1. DTO 클래스 정의
먼저, BookDto 와 BookDetailDto 라는 두 개의 DTO 클래스를 정의한다. 이 클래스들은 데이터베이스의 Book 엔터티에서 필요한 속성만 포함한다.
namespace BookService.Models
{
public class BookDto
{
public int Id { get; set; }
public string Title { get; set; }
public string AuthorName { get; set; }
}
}
namespace BookService.Models
{
public class BookDetailDto
{
public int Id { get; set; }
public string Title { get; set; }
public int Year { get; set; }
public decimal Price { get; set; }
public string AuthorName { get; set; }
public string Genre { get; set; }
}
}
2. GET 메서드에서 DTO 반환
BooksController 클래스에서 DTO를 반환하는 GET 메서드를 정의한다. LINQ의 Select 문을 사용하여 Book 엔터티를 DTO로 변환한다.
// GET api/Books
public IQueryable<BookDto> GetBooks()
{
var books = from b in db.Books
select new BookDto()
{
Id = b.Id,
Title = b.Title,
AuthorName = b.Author.Name
};
return books;
}
// GET api/Books/5
[ResponseType(typeof(BookDetailDto))]
public async Task<IHttpActionResult> GetBook(int id)
{
var book = await db.Books.Include(b => b.Author).Select(b =>
new BookDetailDto()
{
Id = b.Id,
Title = b.Title,
Year = b.Year,
Price = b.Price,
AuthorName = b.Author.Name,
Genre = b.Genre
}).SingleOrDefaultAsync(b => b.Id == id);
if (book == null)
{
return NotFound();
}
return Ok(book);
}
3. POST 메서드에서 DTO 변환
책을 추가하는 POST 메서드에서도 DTO를 반환하도록 수정한다.
[ResponseType(typeof(BookDto))]
public async Task<IHttpActionResult> PostBook(Book book)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Books.Add(book);
await db.SaveChangesAsync();
// Load author name
db.Entry(book).Reference(x => x.Author).Load();
var dto = new BookDto()
{
Id = book.Id,
Title = book.Title,
AuthorName = book.Author.Name
};
return CreatedAtRoute("DefaultApi", new { id = book.Id }, dto);
}
위의 예시는 DTO를 사용하여 데이터베이스 엔터티에서 클라이언트로 전송할 데이터를 정의하고, 이를 통해 클라이언트가 필요한 정보만을 받을 수 있도록 하는 방법을 보여준다.
Create Data Transfer Objects (DTOs)
Describes how to create data transfer objects (DTOs) manually using code to change the shape of the data sent to the client.
learn.microsoft.com
예를 들어, NestJS에서 간단한 서비스와 컨트롤러를 작성하여 의존성 주입을 구현하는 방법은 다음과 같다.
1. 서비스 클래스 정의
import { Injectable } from '@nestjs/common';
@Injectable()
export class CatsService {
private readonly cats: string[] = [];
findAll(): string[] {
return this.cats;
}
}
2. 컨트롤러 클래스 정의
import { Controller, Get } from '@nestjs/common';
import { CatsService } from './cats.service';
@Controller('cats')
export class CatsController {
constructor(private catsService: CatsService) {}
@Get()
async findAll(): Promise<string[]> {
return this.catsService.findAll();
}
}
이 예시에서 CatsService 는 @Injectable() 데코레이터를 통해 NestJS의 의존성 주입 컨테이너에 등록되고, CatsController 에서 생성자 주입을 통해 CatsService 에 접근할 수 있다.
https://docs.nestjs.com/fundamentals/custom-providers
Documentation | NestJS - A progressive Node.js framework
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea
docs.nestjs.com
[CS] HTTP 쿠키와 세션: 웹의 기초 (2) | 2025.01.21 |
---|---|
[CS] 인증과 인가: 보안의 두 기둥 (0) | 2025.01.21 |
[CS] PK와 FK: 데이터베이스 무결성을 위한 필수 요소 (4) | 2025.01.20 |
[CS] DI, IoC, 그리고 ORM: 개발 생산성을 높이는 핵심 개념 완벽 정리 (3) | 2025.01.16 |
[CS] RDBMS와 NoSQL의 차이점: 데이터베이스 선택의 모든 것 (2) | 2025.01.14 |