//match.decorator.ts
class-validator에 있는 공식 문서에 있는 대로 썻다.
import { registerDecorator, ValidationArguments, ValidationOptions } from 'class-validator';

export function IsEqualTo(property: string, validationOptions?: ValidationOptions) {
    return (object: any, propertyName: string) => {
      registerDecorator({
        name: 'isEqualTo', //아무거나 써도 되는 거같다.
        target: object.constructor,
        propertyName,
        constraints: [property],
        options: validationOptions,
        validator: {  //검증 validate는 무조건 실행된다 
          validate(value: any, args: ValidationArguments) { //검증에 성공했을떄 
            console.log(value) //ConfirmPassword의 값이 들어가있다.
          const [relatedPropertyName] = args.constraints;  //args.constraints  == ["password"]
          const relatedValue = (args.object as any)[relatedPropertyName];
          return value === relatedValue; //password와 ConfirmPassword의 값이 같으면 통과한다.
        },
 
        defaultMessage(args: ValidationArguments) {  //검증에 실패했을떄(password와 ConfirmPassword의 값이 않을떄)
          const [relatedPropertyName] = args.constraints;
          return `${propertyName} must match ${relatedPropertyName} exactly`; //오류 메세지를 반환한다.
        },
      },
    });
  };
}
import { IsBoolean, IsEmail , IsOptional, IsString, MinLength } from "class-validator";
import { IsEqualTo } from "src/decorators/match.decorator"; //위에 있는 파일 경로이다
export class CreateAuthDto {
    @IsEmail()
    email : string

    @IsString()
    @MinLength(5,{message : "5글자 이상 입력해주세요"})
    Password : string


    @IsString()
    @IsEqualTo("Password") //비교할 것을 넣어주면 된다.
    ConfirmPassword : string


    @IsBoolean()
    @IsOptional()
    privilege : boolean
}

 

'TypeScript' 카테고리의 다른 글

Interceptor  (0) 2023.12.22
Everyday Types  (0) 2023.12.20
자동 재시작 & 자동 컴파일 .js생성  (1) 2023.12.02

Interceptro을 전역으로 쓰고 싶다면  APP.module에서  APP_INTERCEPTO 를 호출하고 
provider에 전역으로 써줄 interceptor을 써주면 된다.
(모든 모듈에서 직접 인터셉터를 설정할 수 있습니다)


import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';

@Module({
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: LoggingInterceptor,
    },
  ],
})
export class AppModule {}

 

cats.controller.ts 
CatsController에 있는 모든 핸들러에 interceptor이 적용되게 끔 해주는 것이다
@UseInterceptors(new LoggingInterceptor())
export class CatsController {}

'TypeScript' 카테고리의 다른 글

Password validation  (0) 2023.12.25
Everyday Types  (0) 2023.12.20
자동 재시작 & 자동 컴파일 .js생성  (1) 2023.12.02
<Typescript에서 string,number 인것처럼 소문자로 해주어야한다
 number,string, boolean, symbol =  primitive type
 Number, String, Boolean, Symbol = Reference Type>

string : string 타입은 텍스트 데이터를 나타냅니다.
		 작은 따옴표(’), 큰 따옴표(”), 백쿼트(`) 를 사용하여 문자열을 표현할 수 있습니다. 
         
ex) let myName: string = "Alice";
	function greet(name: string) {
  		console.log("Hello, " + name.toUpperCase() + "!!");
	}
    
number : number 타입은 TypeScript에서 사용하는 모든 숫자(short, int, long, float, double)를 나타냅니다
ex) function calculateArea(radius: number): number {
  		return Math.PI * radius * radius;
	}
        
boolean :  boolean 타입은 참(true) 또는 거짓(false) 값을 나타냅니다. 
ex) function isValidPassword(password: string): boolean {
  		return password.length >= 8;
	}
    
any : TypeScript에서 any 타입은 모든 타입의 슈퍼 타입(어떠한 값이든 저장 가능 하지만 이걸 사용한다면 Typescript를 사용하는 이유가 없다)
ex) let obj: any = { x: 0 };
	obj.foo();
	obj();
	obj.bar = 100;
	obj = "hello";
	const n: number = obj;

Object Types : Object type을 정의하려면 해당 속성과 유형을 나열하기만 하면 됩니다.
ex) function printCoord(pt: { x: number; y: number }) {
  		console.log("The coordinate's x value is " + pt.x);
  		console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 3, y: 7 });

Optional Properties : 해당 속성의 일부 또는 전부를 선택 사항으로 지정할 수도 있습니다(?)

ex) function printName(obj: { first: string; last?: string }) {
  		// ...
	}
printName({ first: "Bob" });
printName({ first: "Alice", last: "Alisson" });


 Union Types : 여러 타입 중 하나를 가질 수 있는 변수를 선언할 때 사용
 ex) type StringOrNumber = string | number; 
 
 
 Type Aliases  ||  Interfaces:
 ex) type Point = {
  x: number;
  y: number;
};
 
// Exactly the same as the earlier example
function printCoord(pt: Point) {
  console.log("The coordinate's x value is " + pt.x);
  console.log("The coordinate's y value is " + pt.y);
}
---------------------------------------------------------------
printCoord({ x: 100, y: 100 });

interface Point {
  x: number;
  y: number;
}
 
function printCoord(pt: Point) {
  console.log("The coordinate's x value is " + pt.x);
  console.log("The coordinate's y value is " + pt.y);
}
 
printCoord({ x: 100, y: 100 });

'TypeScript' 카테고리의 다른 글

Password validation  (0) 2023.12.25
Interceptor  (0) 2023.12.22
자동 재시작 & 자동 컴파일 .js생성  (1) 2023.12.02
:: 모든 것은 터미널에서 한 것입니다.


1.npm install --save lite-server //코드를 저장하면 자동으로 재시작

2."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start" : "lite-server" //스크립트에서 start를 lite-server로 해준다.
  }
  
 3.npm start를 하고 실행하면 코드를 저장하면 자동으로 웹에서 즉각 업데이트해준다.
 
 
 4.tsc --init // 파일을 tsc <파일 이름> 을 할 일이 없이 이것을 써준다 그럼 tsconfig-.json이라는 파일이 생기면 성공이다.
 
 5.tsc //내가 지정한 경로에 있는 모든 ts파일이 자동으로 js파일로 일일이 하나씩 바꿀 필요없이 다 바뀐다
 
 
 6.tsc -w //감시모드로 내가 코드를 바꾸면 즉각으로 자동으로 js에서 이를 반영해 바꾸어준다 (tsc를 직접 안쳐줘도 된다)
 
 
 7(컴파일하고싶지 않은 파일이 있을때 exclude).
 tsconfig.json파일 아래에다가 
 "exclude": [
  "analytics.ts"
  "*.dev.ts"
 
  
  ]
 파일명을 적어주면 그 파일은 컴파일이 안된다(compilerOptions{}안에 써줘야함)
 .dev.ts로 끝나는 모든 파일을 컴파일을 안한다
 //node_modules는 자동으로 컴파일에서 제외된다.
 
 
 7-1. exclude외에 include, file 등등이 존재한다.
 
  
 결론 : 1 -> 2 -> 3 -> 4 ->5 or 6

'TypeScript' 카테고리의 다른 글

Password validation  (0) 2023.12.25
Interceptor  (0) 2023.12.22
Everyday Types  (0) 2023.12.20

+ Recent posts