NestJs setting up Typescript class properties asynchronously results in undefined

30 views Asked by At

I have some microservices setup in NestJs using Typescript: one stores and retrieves configuration information: I am concerned with the client one. I am trying to set up a class that will make Axios requests for me. During it's construction, I would like to retrieve the baseUrl from my configuration service and store it so that it is ready for use. The request is made to the configuration service (and I get the response), but when I later try to retrieve it, the class property is undefined.

I have included an example of what I am trying, but I added an extra assignment to the baseUrl, and when I later go to retrieve it, I get the 'Something Wrong':

@Injectable()
export class MyService extends ApiClient {
    protected readonly logger = new Logger(MyService.name);

    constructor(protected readonly config: ConfigClientService) {
        super(config);
    }

    async setupBaseUrl() {
        this.baseUrl = 'Something Wrong';
        this.baseUrl = await this.config.get('serviceUrl');
        this.logger.debug('Normal');
        return true;
    }

    async printBaseUrl() {
        this.logger.debug(this.baseUrl);
        return 'Done';
    }
}

@Injectable()
export abstract class ApiClient {
    protected abstract readonly logger: Logger;
    protected baseUrl: string;

    constructor(protected readonly config: ConfigClientService) {
        this.setupBaseUrl();
    }

    async setupBaseUrl() {
        this.logger.debug('Base Setup');
        this.baseUrl = 'Nothing';
        return true;
    }
}
0

There are 0 answers