Cannot read property 'create' of undefined in TS

天涯浪子 提交于 2020-06-23 14:00:08

问题


I create an function to create new user in NestJS/TypeScript,

after launch my function, my console throw me this:

TypeError: Cannot read property 'create' of undefined
    at Repository.create (/mnt/c/Users/Maciek/Desktop/personal-data/node_modules/typeorm/repository/Repository.js:49:29)
    at UserService.create (/mnt/c/Users/Maciek/Desktop/personal-data/dist/user/user.service.js:60:40)
    at AuthController.register (/mnt/c/Users/Maciek/Desktop/personal-data/dist/auth/auth.controller.js:38:45)

can someone tell what i have doing wrong?

rest of my code:

export class CrudService<T extends ExtendedEntity>{
    protected repository: Repository<T>;

    constructor(
        repository?: Repository<T>
    ){
        if(repository){
            this.repository = repository;
        }
    }

    public async create(data: DeepPartial<T>): Promise<T> {
        const entity: T = this.repository.create(data);

        await this.validate(entity, {
            groups: ['create']
        });
        return entity.save();
    }
}
import { CrudService } from 'src/helpers/service/crud-service';

@Injectable()
export class UserService extends CrudService<UserEntity>{
    private logger = new Logger(UserService.name);
    constructor(
        protected readonly repository: Repository<UserEntity>,
    ) {
        super();
    }

    public async create(data: DeepPartial<UserEntity>): Promise<UserEntity> {
        const entity = this.repository.create(data);
        await this.validate(entity);
        entity.hashPassword();
        if(!entity.createdAt){
            entity.createdAt = new Date;
        }
        const user = await entity.save();
        return user;
    }
}
@Controller('api/auth')
@ApiTags('auth')
export class AuthController {
    private logger = new Logger(AuthController.name);

    constructor(
        private readonly userService: UserService
    ){}



    @Post('register')
    @ApiBody({ required: true, type: UserEntityDto })
    @ApiResponse({ status: 204, description: 'NO_CONTENT'})
    public async register(@Body() data: DeepPartial<UserEntity>): Promise<void> {
        const user = await this.userService.create(data);
        this.logger.debug(`[register] User ${data.email} register`);
    }
}

来源:https://stackoverflow.com/questions/62331976/cannot-read-property-create-of-undefined-in-ts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!