Skip to content
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
85 changes: 85 additions & 0 deletions src/core/decorators/strict-boolean.decorator.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { BadRequestException, ValidationPipe } from '@nestjs/common';
import { Type } from 'class-transformer';
import { ValidateNested } from 'class-validator';
import { SubmitDeclarationDto } from '../../declaration/dto/submit-declaration.dto';
import { CreateQuestionTemplateDto } from '../../question-template/dto/create-question-template.dto';
import { StrictBoolean } from './strict-boolean.decorator';

// src/main.ts의 전역 ValidationPipe와 같은 설정 (implicit conversion이 켜져 있는 상태에서 검증해야 의미가 있다)
const pipe = new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
transformOptions: { enableImplicitConversion: true },
});

async function transform<T>(metatype: new () => T, body: unknown): Promise<T> {
return pipe.transform(body, { type: 'body', metatype });
}

class FlagDto {
@StrictBoolean()
flag!: boolean;
}

class NestedDto {
@ValidateNested()
@Type(() => FlagDto)
inner!: FlagDto;
}

describe('StrictBoolean', () => {
it.each([true, false])('진짜 boolean(%s)은 그대로 통과한다', async (value) => {
await expect(transform(FlagDto, { flag: value })).resolves.toMatchObject({ flag: value });
});

it.each(['false', 'true', 'YES', 'HOLD', 'NO', 1, 0, '', null])(
'%p는 true/false로 바뀌지 않고 400으로 거부된다',
async (value) => {
await expect(transform(FlagDto, { flag: value })).rejects.toBeInstanceOf(BadRequestException);
},
);

it('중첩 DTO 안에서도 원래 값으로 검사한다', async () => {
await expect(transform(NestedDto, { inner: { flag: 'false' } })).rejects.toBeInstanceOf(BadRequestException);
await expect(transform(NestedDto, { inner: { flag: false } })).resolves.toMatchObject({ inner: { flag: false } });
});

it('비교: 그냥 @IsBoolean이었다면 "false"가 true로 바뀌어 통과했다 (implicit conversion)', async () => {
const { IsBoolean } = await import('class-validator');
class LooseDto {
@IsBoolean()
flag!: boolean;
}
await expect(transform(LooseDto, { flag: 'false' })).resolves.toMatchObject({ flag: true });
});
});

describe('적용된 DTO', () => {
const consents = { evaluationAgreed: true, dataAccessAgreed: true, evidenceRetentionAgreed: true, consentVersion: '2026-10-01' };

it.each(['evaluationAgreed', 'dataAccessAgreed', 'evidenceRetentionAgreed'])(
'자기선언 동의 %s에 "false" 문자열을 보내면 400 (동의로 저장되지 않음)',
async (field) => {
await expect(
transform(SubmitDeclarationDto, { answers: [], consents: { ...consents, [field]: 'false' } }),
).rejects.toBeInstanceOf(BadRequestException);
},
);

it('자기선언 동의가 진짜 boolean이면 그대로 전달된다 (false도 false로)', async () => {
const dto = await transform(SubmitDeclarationDto, { answers: [], consents: { ...consents, dataAccessAgreed: false } });
expect(dto.consents.dataAccessAgreed).toBe(false);
expect(dto.consents.evaluationAgreed).toBe(true);
});

it.each(['required', 'evaluationEnabled'])('질문 템플릿 %s에 "false" 문자열을 보내면 400', async (field) => {
const question = {
order: 1, type: 'SCORE', text: '질문', required: true, scoreMin: 1, scoreMax: 10, evaluationEnabled: true,
[field]: 'false',
};
await expect(
transform(CreateQuestionTemplateDto, { name: '템플릿', questions: [question] }),
).rejects.toBeInstanceOf(BadRequestException);
});
});
18 changes: 18 additions & 0 deletions src/core/decorators/strict-boolean.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { applyDecorators } from '@nestjs/common';
import { Transform } from 'class-transformer';
import { IsBoolean, ValidationOptions } from 'class-validator';

/**
* 진짜 boolean(true/false)만 통과시킨다.
*
* 전역 ValidationPipe의 enableImplicitConversion이 boolean 필드를 검증 전에 Boolean(값)으로 바꾸기 때문에
* 그냥 @IsBoolean()만 쓰면 "false"·"YES"·1 같은 값이 true로 바뀌어 통과한다.
* 동의 여부·재고용 의사처럼 법적 의미가 있는 값이 뒤바뀌지 않도록, 변환 전 원래 값으로 검사한다.
*/
export function StrictBoolean(validationOptions?: ValidationOptions) {
return applyDecorators(
// obj는 변환 전 원본 요청 값. 암묵 변환된 값 대신 원본을 그대로 검증에 넘긴다
Transform(({ obj, key }) => obj[key]),
IsBoolean(validationOptions),
);
}
9 changes: 5 additions & 4 deletions src/declaration/dto/submit-declaration.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import {
IsArray,
IsBoolean,
IsNotEmpty,
IsNumber,
IsOptional,
IsString,
ValidateNested,
} from 'class-validator';
import { StrictBoolean } from '../../core/decorators/strict-boolean.decorator';

/**
* 질문 유형에 맞는 필드 하나만 보낸다. SCORE → answerScore, SINGLE_CHOICE → answerOptionId, TEXT → answerText
Expand Down Expand Up @@ -36,17 +36,18 @@ export class AnswerDto {
answerText?: string;
}

// 동의 여부는 진짜 boolean만 허용 ("false" 문자열이 동의로 바뀌지 않도록)
export class DeclarationConsentsDto {
@ApiProperty({ example: true, description: '평가 활용 동의' })
@IsBoolean()
@StrictBoolean()
evaluationAgreed!: boolean;

@ApiProperty({ example: true, description: '정보 열람 동의' })
@IsBoolean()
@StrictBoolean()
dataAccessAgreed!: boolean;

@ApiProperty({ example: true, description: '증빙 보관 동의' })
@IsBoolean()
@StrictBoolean()
evidenceRetentionAgreed!: boolean;

@ApiProperty({ example: '2026-10-01', description: '질문지 조회 응답의 consentVersion' })
Expand Down
6 changes: 3 additions & 3 deletions src/question-template/dto/question.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { QuestionType } from '@prisma/client';
import {
IsArray,
IsBoolean,
IsEnum,
IsInt,
IsString,
Min,
ValidateIf,
} from 'class-validator';
import { StrictBoolean } from '../../core/decorators/strict-boolean.decorator';

/**
* 템플릿 질문 1개. 여기서는 형식(타입)만 검사하고(400),
Expand All @@ -30,7 +30,7 @@ export class QuestionDto {
text!: string;

@ApiProperty({ example: true })
@IsBoolean()
@StrictBoolean()
required!: boolean;

@ApiPropertyOptional({ example: 1, description: 'SCORE 필수. 1 이상' })
Expand Down Expand Up @@ -59,6 +59,6 @@ export class QuestionDto {
maxLength?: number;

@ApiProperty({ example: true, description: '퇴사 평가 항목으로 사용할지 여부' })
@IsBoolean()
@StrictBoolean()
evaluationEnabled!: boolean;
}
Loading