Search code examples
javascripttypescripttypeorm

Initialize Promises class fields in the constructor method


I had done a test here with repositories, and this is the test:

export default class UserService {
    private userRepository: Repository<UserModel>;
    private connection: Connection;

    private async initialize(): Promise<any> {
        return createConnection()
        .then(v => this.connection = v)
        .then(_ => this.userRepository = this.connection.getRepository(UserModel))
      }

    constructor() {
    }

    public async findByUsername(username: string): Promise<UserModel> {
        let user: any;

        if(this.userRepository == undefined) {
            await this.initialize();
        }

        await this.userRepository.findOne({username: username}).then(v => user = v);
        return user;
    }

}

It's working, but the lint/TS Compiler is saying: the class fields userRepository and connection was not initialized in the constructor method.

All right, but this fields is of type Promise and the constructor is a sincronous method, so, how can I do the constructor initialize this fields?

Thanks


Solution

  • You can consider something like this:

    export default class UserService {
      private connection: Promise<Connection> = createConnection();
      private userRepository: Promise<Repository<UserModel>> = this.connection.then(c =>
        c.getRepository(UserModel),
      );
    
      public async findByUsername(username: string): Promise<UserModel> {
        const userRepository = await this.userRepository;
    
        return await userRepository.findOne({ username });
      }
    }