ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Nest.js] 9 - Authentification - module/components
    Nest.js 2021. 9. 13. 18:44

    Contents
    1. AuthModule
    2. CLI - module, service, controller
    3. Entity, repository
    4. DTO
    5. DI


    1. AuthModule


    2. CLI - module, service, controller

    $ nest generate module auth
    
    $ nest generate service auth --no-spec
    
    $ nest generate controller auth --no-spec


    3. Entity, Repository

    - src/auth/user.entity.ts

    import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
    
    @Entity()
    export class User extends BaseEntity {
      @PrimaryGeneratedColumn()
      id: number;
    
      @Column()
      username: string;
    
      @Column()
      password: string;
    }

     

    - src/auth/user.repository.ts

    import { EntityRepository, Repository } from 'typeorm';
    import { User } from './user.entity';
    
    @EntityRepository(User)
    export class UserRepository extends Repository<User> {}

    - register this into where it needed, auth.module.ts below.

     

    - src/auth/auth.module.ts

    ...
    import { UserRepository } from './user.repository';
    
    @Module({
      imports: [
        TypeOrmModule.forFeature([UserRepository])
      ],
      ...
    })
    export class AuthModule {}

    4. DTO(Data Transfer Object)

    - src/auth/dto/auth-credential.dto.ts

    import { IsString, Matches, MaxLength, MinLength } from 'class-validator'; // 1
    
    export class AuthCredentialsDto {
      @IsString()
      @MinLength(4)
      @MaxLength(20)
      username: string;
    
      @IsString()
      @MinLength(4)
      @MaxLength(20)
      @Matches(/^[a-zA-Z0-9]*$/, {
        message: 'password only accepts english and number',
      })
      password: string;
    }

    // 1. global pipe will validate this dto with the decorators.


    5. DI(Dependency Injection)

    - src/auth/auth.controller.ts

    import { Controller } from '@nestjs/common';
    import { AuthService } from './auth.service';
    
    @Controller('auth')
    export class AuthController {
      constructor(private userService: AuthService) {}
    }

     

    - src/auth/auth.service.ts

    import { Injectable } from '@nestjs/common';
    import { InjectRepository } from '@nestjs/typeorm';
    import { UserRepository } from './user.repository';
    
    @Injectable()
    export class AuthService {
      constructor(
        @InjectRepository(UserRepository)
        private userRepository: UserRepository,
      ) {}
    }

     

Designed by Tistory.