2

I am trying to create microservices via Nestjs and Nats but I am getting an error Error: Empty response. There are no subscribers listening to that message ("checkUserExists") For Now I have only Gateway and Auth microservice All necessary code and files are described below

Gateway code

import { join } from 'path';
import basicAuth from 'express-basic-auth';
import { NestFactory } from '@nestjs/core';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
import { NestExpressApplication } from '@nestjs/platform-express';
import { Logger, ValidationPipe } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { SwaggerModule } from '@nestjs/swagger';
import { AppModule } from './app/app.module';
import { ApiModulesList } from './api/api.modules.list';
import { GlobalExceptionFilter } from './exceptions';
import { swaggerConfig } from './swagger';

const logger = new Logger('Gateway Service');

const bootstrap = async () => {
    const app = await NestFactory.create<NestExpressApplication>(AppModule);

    const configService = new ConfigService();
    const port = parseInt(configService.get('API_PORT', '3000'), 10);
    const apiRoutePrefix = configService.get('API_ROUTE_PREFIX', 'api');
    const apiDoc = configService.get('SWAGGER_DOC_URL', 'api-docs');
    const isSwaggerOn = configService.get('IS_SWAGGER_UI_ACTIVE', 'false').toLowerCase() === 'true';

    app.useGlobalPipes(new ValidationPipe({ exceptionFactory: (errors) => errors, transform: true, whitelist: true }));
    app.useGlobalFilters(new GlobalExceptionFilter());
    app.enable('trust proxy');

    app.useStaticAssets(join(__dirname, '..', 'public'));

    if (isSwaggerOn) {
        if (configService.get('NODE_ENV', '') !== 'development') {
            app.use(
                [`/${apiDoc}`, `/${apiDoc}-json`],
                basicAuth({
                    challenge: true,
                    users: {
                        [configService.get('BASIC_AUTH_USER_NAME', 'admin')]: configService.get(
                            'BASIC_AUTH_PASSWORD',
                            'Messapps@1'
                        ),
                    },
                })
            );
        }
        const apiGuideLink = configService.get('API_GUIDE_LINK', '');
        const appName = configService.get('APPNAME', 'Project name');
        const document = SwaggerModule.createDocument(app, swaggerConfig({ appName, port, apiGuideLink }), {
            include: ApiModulesList,
        });
        SwaggerModule.setup(apiDoc, app, document);
    }
    const natsToken = configService.get('NATS_TOKEN');
    const natsHost = configService.get('NATS_HOST', 'localhost');
    const natsPort = configService.get('NATS_PORT', '4222');

    const natsMicroservice = app.connectMicroservice<MicroserviceOptions>({
        transport: Transport.NATS,
        options: {
            servers: [`nats://${natsHost}:${natsPort}`],
            token: natsToken,
        },
    });

    await app.startAllMicroservices();

    await app.listen(port);

    logger.debug(`API Server started at http://localhost:${port}/${apiRoutePrefix}`);
    isSwaggerOn
        ? logger.debug(`Swagger Docs runs at http://localhost${port ? ':' + port : ''}/${apiDoc} `)
        : logger.debug('Swagger Docs is OFF');
};

bootstrap().catch((error) => {
    logger.error(error);
});

Gateway Service

import { Inject, Injectable } from '@nestjs/common';
import { CheckUserExistsRequest, CheckUserExistsResponse, AuthSuccessResponse, AuthSignUpRequest } from './dto';
import { AuthType } from './auth.enums';
import { Observable } from 'rxjs';
import { ClientProxy } from '@nestjs/microservices';

@Injectable()
export class AuthService {
    constructor(@Inject('GATEWAY_AUTH_PUBLISHER') private natsClient: ClientProxy) {}

    checkUserExists(dto: CheckUserExistsRequest): Observable<CheckUserExistsResponse> {
        return this.natsClient.send<CheckUserExistsResponse, CheckUserExistsRequest>('checkUserExists', dto);
    }

}

Microservice Listener

import { Inject, Injectable } from '@nestjs/common';
import { ClientProxy, MessagePattern } from '@nestjs/microservices';
import { CheckUserExistsRequest, CheckUserExistsResponse } from './dto';

@Injectable()
export class AppService {
    constructor(@Inject('AUTH_SERVICE') private natsClient: ClientProxy) {}

    @MessagePattern('checkUserExists')
    async checkUserExistsRes(dto: CheckUserExistsRequest): Promise<CheckUserExistsResponse> {
        console.log('checkUserExistsRes', dto);
        return { exists: true };
    }
}

I have tried everything but didnt get any success if anyone knows how to resolve this issue will be very thankful!

0 Answers0