logo

@jihyunlab/json-validator

@jihyunlab/json-validator는 JSON Schema와 ajv 기반으로, NestJS에서 Validation Pipe를 보다 쉽고 편리하게 구성할 수 있도록 개발되었습니다.
@jihyunlab/json-validator는 NestJS 환경이 아니어도 사용할 수 있는 JsonValidationHelper도 제공합니다.

설치

프로젝트 폴더에서 @jihyunlab/json-validator를 설치합니다.

npm i @jihyunlab/json-validator

사용 예

요청 검증을 위한 JSON Schema를 정의합니다.
컨트롤러의 요청 수신 방식에 따라 query, parameter, body에 대한 JSON Schema를 구성할 수 있습니다.

import { JsonRequestSchema } from '@jihyunlab/json-validator';

export const UserJsonSchema: Record<'find' | 'findOne', JsonRequestSchema> = {
  find: {
    query: {
      type: 'object',
      properties: {
        name: {
          type: 'string',
          pattern: '^[^\\s][\\s\\S]{0,}$',
        },
      },
      required: ['name'],
    },
  },
  findOne: {
    parameter: {
      type: 'object',
      properties: {
        email: {
          type: 'string',
          pattern: '^[\\w.-]+@jihyunlab\\.com$',
        },
      },
      required: ['email'],
    },
  },
};

정의된 JSON Schema와 JsonValidationPipe를 사용하여 NestJS 컨트롤러에서 Validation Pipe를 간단하게 구현할 수 있습니다.

import { JsonValidationPipe } from '@jihyunlab/json-validator';
import { UserJsonSchema } from '../json-schemas/user.json-schema';

@Controller('/user')
export class UserController {
  constructor() {}

  @Get()
  @UsePipes(new JsonValidationPipe(UserJsonSchema.find))
  async find(
    @Query()
    query: {
      name: string;
    },
    @Res() response: Response
  ) {...}
  ...
}

JsonValidationPipe에서 검증이 실패하면, ajv에서 생성된 오류가 HTTP 응답으로 반환됩니다.

{
  "message": [
    {
      "instancePath": "/name",
      "schemaPath": "#/properties/name/pattern",
      "keyword": "pattern",
      "params": {
        "pattern": "^[^\\s][\\s\\S]{0,}$"
      },
      "message": "must match pattern \"^[^\\s][\\s\\S]{0,}$\""
    }
  ],
  "error": "Bad Request",
  "statusCode": 400
}

JsonValidationHelper를 사용하면 NestJS 환경이 아닐 때에도 요청을 간단하게 검증할 수 있습니다.

import { JsonValidationHelper } from '@jihyunlab/json-validator';
import { UserJsonSchema } from '../json-schemas/user.json-schema';

const result = await JsonValidationHelper.validate(
  query,
  UserJsonSchema.find.query || {}
);
{
  "valid": true,
  "message": "The validation was passed."
}

검증에 실패하면, 오류 정보가 포함된 결과가 반환됩니다.

{
  "valid": false,
  "message": "The validation has failed.",
  "errors": [
    {
      "instancePath": "/name",
      "schemaPath": "#/properties/name/pattern",
      "keyword": "pattern",
      "params": {
        "pattern": "^[^\\s][\\s\\S]{0,}$"
      },
      "message": "must match pattern \"^[^\\s][\\s\\S]{0,}$\""
    }
  ]
}

JsonValidationHelper를 사용하면 개별 값도 간단하게 검증할 수 있습니다.

const result = await JsonValidationHelper.validate(query.name, {
  type: 'string',
  pattern: '^[^\\s][\\s\\S]{0,}$',
});

라이센스

Open source licensed as MIT.

logo

ⓒ 2023-2024 JihyunLab. All rights reserved.

info@jihyunlab.com