π 곡λΆνλ μ§μ§μνμΉ΄λ μ²μμ΄μ§?
[Nest JS λ‘ CRUD κ²μν λ§λ€κΈ°] (24) μ μ μ΄λ¦μ μ λν¬ν κ° μ£ΌκΈ° λ³Έλ¬Έ
π©π» λ°±μλ(Back-End)/Nest js
[Nest JS λ‘ CRUD κ²μν λ§λ€κΈ°] (24) μ μ μ΄λ¦μ μ λν¬ν κ° μ£ΌκΈ°
μ§μ§μνμΉ΄ 2023. 6. 8. 16:58728x90
λ°μν
<λ³Έ λΈλ‘κ·Έλ John Ahn μ μ νλΈλ₯Ό μ°Έκ³ ν΄μ 곡λΆνλ©° μμ±νμμ΅λλ€ :-)>
=> λ°λΌνλ©΄μ λ°°μ°λ NestJS
π§Έ μ μ μ΄λ¦μ μ λν¬ν κ° μ£ΌκΈ°
μ μ μμ±ν λ μ μ μ΄λ¦μ΄ μ΄λ―Έ μ¬μ©λλ μ μ μ΄λ¦μ μ¬μ©νλ € νλ€λ©΄ μλ¬ λ³΄λ΄κΈ°
1) repository μμ findOne λ©μλ μ΄μ©νμ¬ μ΄λ―Έ κ°μ μ μ μ΄λ¦μ κ°μ§ μμ΄λκ° μλμ§ νμΈ
μλ€λ©΄ λ°μ΄ν° μ μ₯νκΈ°
-> λ°μ΄ν°λ² μ΄μ€ μ²λ¦¬λ₯Ό λλ² ν΄μΌ ν¨
2) λ°μ΄ν°λ² μ΄μ€ λ 벨μμ λ§μ½ κ°μ μ΄λ¦μ κ°μ§ μ μ κ° μλ€λ©΄ μλ¬ λμ§κΈ°
π§Έ λ°μ΄ν°λ² μ΄μ€ λ 벨μμ λ§μ½ κ°μ μ΄λ¦μ κ°μ§ μ μ κ° μλ€λ©΄ μλ¬ λμ§κΈ°
π user.entity.ts
import { BaseEntity, Column, Entity, PrimaryColumn, PrimaryGeneratedColumn, Unique } from "typeorm";
@Entity()
// μ μ μ΄λ¦μ μ λν¬ν κ° μ£ΌκΈ°
@Unique(["username"])
export class User extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
username: string;
@Column()
password: string;
}
π user.repository.ts
import { CustomRepositoryCannotInheritRepositoryError, EntityRepository, Repository } from "typeorm";
import { User } from "./user.entity";
import { AuthCredentialsDto } from "./dto/auth-credential.dto";
import { ConflictException, InternalServerErrorException } from "@nestjs/common";
@EntityRepository(User)
export class UserRepository extends Repository<User> {
async createUser(authCredentialsDto: AuthCredentialsDto): Promise<void> {
const { username, password } = authCredentialsDto;
const user = this.create({ username, password });
// λ°μ΄ν°λ² μ΄μ€ λ 벨μμ λ§μ½ κ°μ μ΄λ¦μ κ°μ§ μ μ κ° μλ€λ©΄ μλ¬ λμ§κΈ°
try {
await this.save(user);
} catch (error) {
if (error.code === "23505") {
throw new ConflictException("Existing username");
} else {
throw new InternalServerErrorException();
}
}
}
}
728x90
λ°μν
'π©βπ» λ°±μλ(Back-End) > Nest js' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
Comments