0

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;
    }
}
Rob
  • 341
  • 1
  • 3
  • 11
  • How are you providing and calling `MyService#printBaseUrl`? Are you certain `this.config.get('serviceUrl')` returns what you think? I would assume if you log `this.baseUrl` and get back `undefined` then the issue is in the config service, not with how you're setting the values – Jay McDoniel Sep 01 '23 at 14:52
  • If I log the this.baseUrl right after I await it, I get the actual url. And I log in the config service, and it is showing the proper retrieval and response. – Rob Sep 01 '23 at 14:55
  • So something else is setting it to `undefined`? Do you clear out the URL anywhere? – Jay McDoniel Sep 01 '23 at 14:56
  • No, there really is no other code besides these functions for these classes (I am adding them to a larger microservice). It just does not make any sense to me. I was wondering if I was confused about the this somewhere, but I can't see how that would be. It just doesn't seem to like the asynchonous response, and sends it into the ether. – Rob Sep 01 '23 at 15:06
  • I did add the @Injectable() above the abstract class, but that didn't seem to make a difference. – Rob Sep 01 '23 at 15:07
  • OK, I did figure it out, there was an extra dependancy being injected that was causing some weird behaviour. Once I removed it, it seems to work. – Rob Sep 01 '23 at 15:20

0 Answers0