# Serialization

## Serialization

시리얼 라이저는 실제 응답을 보내기 전에 **데이터 조작**에 대한 깨끗한 추상화 계층을 제공합니다. 예를 들어, 사용자 비밀번호와 같은 민감한 데이터는 항상 최종 응답에서 제외해야 합니다. 또한 특정 속성에는 추가 변환이 필요할 수 있습니다. 예를 들어 전체 데이터베이스 엔터티를 보내지 않으려는 경우를 가정해 보겠습니다. 대신, 우리는 `id`와 `name` 만 고르고 싶습니다. 나머지는 자동으로 제거해야합니다. 불행히도 모든 엔티티를 수동으로 매핑하면 많은 혼란이 생길 수 있습니다.

## Overview

Nest는 이러한 작업을 수행하는 간단한 방법을 제공하기 위해 `ClassSerializerInterceptor`클래스를 제공합니다. [class-transformer](https://github.com/typestack/class-transformer) 패키지를 사용하여 선언적이고 확장 가능한 객체 변환 방법을 제공합니다. 기본적으로 `ClassSerializerInterceptor`는 메소드에서 리턴된 값을 가져 와서 [class-transformer](https://github.com/typestack/class-transformer) 패키지에서 serializ`classToPlain()`함수를 호출합니다.

## Exclude properties

다음 엔터티에서 `password` 속성을 자동으로 제외한다고 가정 해 봅시다.

```typescript
import { Exclude } from 'class-transformer';

export class UserEntity {
  id: number;
  firstName: string;
  lastName: string;

  @Exclude()
  password: string;

  constructor(partial: Partial<UserEntity>) {
    Object.assign(this, partial);
  }
}
```

그런 다음 컨트롤러의 메소드에서 이 클래스의 인스턴스를 직접 리턴하십시오.

```typescript
@UseInterceptors(ClassSerializerInterceptor)
@Get()
findOne(): UserEntity {
  return new UserEntity({
    id: 1,
    firstName: 'Kamil',
    lastName: 'Mysliwiec',
    password: 'password',
  });
}
```

> info **힌트** `ClassSerializerInterceptor`는 `@nestjs/common` 패키지에서 가져옵니다.

이제 이 엔드 포인트를 호출하면 다음과 같은 응답이 나타납니다.

```javascript
{
  "id": 1,
  "firstName": "Kamil",
  "lastName": "Mysliwiec"
}
```

## Expose properties

미리 계산된 속성을 노출하려면 `@Expose()`데코레이터를 사용하십시오.

```typescript
@Expose()
get fullName(): string {
  return `${this.firstName} ${this.lastName}`;
}
```

## Transform

`@Transform()`데코레이터를 사용하여 추가 데이터 변환을 수행할 수 있습니다. 예를 들어, 전체 객체를 반환하는 대신 `RoleEntity`의 이름을 선택하려고합니다.

```typescript
@Transform(role => role.name)
role: RoleEntity;
```

## Pass options

변형 옵션은 특정 요인에 따라 달라질 수 있습니다. 기본 설정을 덮어 쓰려면 `@SerializeOptions()`데코레이터를 사용하십시오.

```typescript
@SerializeOptions({
  excludePrefixes: ['_'],
})
@Get()
findOne(): UserEntity {
  return {};
}
```

> info **힌트** `@SerializeOptions()` 데코레이터는 `@nestjs/common` 패키지에서 가져옵니다.

이 옵션은 `classToPlain()` 함수의 두 번째 인수로 전달됩니다.

## Websockets & Microservices

이 모든 지침은 사용중인 전송 방법에 관계없이 WebSocket과 마이크로 서비스에 관한 것입니다.

## Learn more

사용 가능한 데코레이터, 옵션에 대한 자세한 내용은 이 [페이지](https://github.com/typestack/class-transformer)를 참조하십시오.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jakekwak.gitbook.io/nestjs/techniques/serialization.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
