Node.jsのclass-validatorでユニークバリデーション
nodejsのclass-validatorについて。 https://github.com/typestack/class-validator class-validatorインストール modelクラスのプロパティにアノテーションでバリデーションルールを記載し、1つのメソッドでバリデーションチェックしてくれるライブラリだ。 ほとんど使い方は公式にある通りでする理解できるが、ユニークチェックに少しハマったのでメモ。 class-validatorでユニークバリデーションチェック Hogeクラスはhogeテーブルのモデルで、emailカラムの重複チェックをしたい時は以下のようにする。 import { validate, registerDecorator, ValidationOptions, ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from "class-validator"; export class Hoge { @Unique({ message: "このメールアドレスは既に使用されています。" }) public email: string null = null; } @ValidatorConstraint({async: true}) export class UniqueConstraint implements ValidatorConstraintInterface { async validate(value: any, args: ValidationArguments) { // DBに接続してvalueの一致レコードを取得 // 一致レコードが存在する場合はfalse(バリデーションエラー) return true } } export function Unique(validationOptions?
2019/05/19 14:47