JS/Nest.js
[Nest JS] 회원가입 구현 / TypeError: this.userRepository.createUser is not a function 해결
Mini_96
2024. 8. 18. 13:00
* dto 생성
export class AuthCredentialsDto{
username : string;
password : string;
}
* 리포지토리에서 db 접근 메소드 구현
@Injectable()
export class UserRepository extends Repository<User>{
constructor(dataSource: DataSource) {
super(User, dataSource.createEntityManager());
}
async createUser(authCredentialsDto : AuthCredentialsDto){
const {username, password} = authCredentialsDto;
const user = this.create({username,password}); //리포지토리.create => db저장용객체로 만들어줌
await this.save(user);
}
}
* 서비스에서 사용
async signUp(autoCredentialsDto : AuthCredentialsDto){
return this.userRepository.createUser(autoCredentialsDto);
}
* 컨트롤러
컨트롤러는 서비스에만 의존해야함에 주의.
import { Body, Controller, Post } from "@nestjs/common";
import { AuthService } from "./auth.service";
import { AuthCredentialsDto } from "./dto/auth-credentials.dto";
@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {} //서비스만 사용해야함에 주의
@Post('/singup')
signUp(@Body() authcredentialsDto : AuthCredentialsDto){
return this.authService.signUp(authcredentialsDto);
}
}
* TypeError: this.userRepository.createUser is not a function 해결
모듈 > providers에 UserRepository 추가 해주면 됨.
@Module({
imports:[
TypeOrmModule.forFeature([UserRepository])
],
controllers: [AuthController],
providers: [AuthService, UserRepository]
})
export class AuthModule {}
추가확인사항
@Injectable()
export class UserRepository extends Repository<User>{
constructor(dataSource: DataSource) {
super(User, dataSource.createEntityManager());
}
export class AuthService {
constructor(
@InjectRepository(UserRepository) //변수에 의존성 주입해줘
private userRepository: UserRepository) {
}