Home > Software engineering >  Nest can't resolve dependencies
Nest can't resolve dependencies

Time:01-03

I ran into a problem with NestJS dependencies, I just started learning Nest and still don't quite understand how to build the structure correctly.

Nest can't resolve dependencies of the ChatGateway (?). Please make sure that the argument ChatAuth at index [0] is available in the ChatGateway context.

My error in terminal My error in terminal

chat.module.ts `

import { Module } from '@nestjs/common';
import { ChatAuth } from './chat.middlewares';
import { ChatGateway } from './chat.gateway';
import { AuthHelper } from '../auth/auth.helper';
import { JwtStrategy } from '../auth/auth.strategy';

@Module({
  imports: [ChatGateway, ChatAuth],
  controllers: [],
  providers: [AuthHelper, JwtStrategy],
})
export class ChatModule {}

`

chat.gateway.ts `

import {
  SubscribeMessage,
  WebSocketGateway,
  OnGatewayInit,
  WebSocketServer,
  OnGatewayConnection,
  OnGatewayDisconnect,
  MessageBody,
} from '@nestjs/websockets';
import { Logger } from '@nestjs/common';
import { Socket, Server } from 'socket.io';
import { ChatAuth } from './chat.middlewares';

@WebSocketGateway(7000)
export class ChatGateway
  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
  @WebSocketServer() server: Server;

  private chatAuthHelper: ChatAuth;
  private logger: Logger = new Logger('ChatGateway');

  constructor(chatAuthHelper: ChatAuth) {
    this.chatAuthHelper = chatAuthHelper;
  }

  @SubscribeMessage('msgToServer')
  handleMessage(client: Socket, payload: string): void {
    console.log(payload);
    this.server.emit('msgToClient', payload);
  }

  @SubscribeMessage('events')
  handleEvent(@MessageBody() data: string): void {
    const parsed = JSON.parse(JSON.stringify(data));
    parsed.msg = parsed.msg   ' 3';
    this.server.emit('onMessage', {
      msg: 'New message',
      content: parsed.msg,
    });
  }
  afterInit(server: Server) {
    this.logger.log('Init');
  }

  handleDisconnect(client: Socket) {
    this.logger.log(`Client disconnected: ${client.id}`);
  }

  handleConnection(client: Socket, ...args: any[]) {
    if (client.handshake.headers.authorization) {
      const guard = this.chatAuthHelper.use(
        client.handshake.headers.authorization,
      );
    }
    this.logger.log(`Client connected: ${client.id}`);
  }
}

`

chat.middlewares.ts `

import { Injectable, NestMiddleware } from '@nestjs/common';
import { AuthHelper } from '../auth/auth.helper';

@Injectable()
export class ChatAuth implements NestMiddleware {
  private helper: AuthHelper;
  constructor(helper: AuthHelper) {
    this.helper = helper;
  }

  public async use(token): Promise<object> {
    const currentToken = token.split(' ')[1];
    const user = await this.helper.validate(currentToken);
    console.log(JSON.stringify(user));
    return user;
  }
}

`

app.module.ts `

import { Module } from '@nestjs/common';
import * as path from 'path';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { getEnvPath } from './common/helper/env.helper';
import { TypeOrmConfigService } from './shared/typeorm/typeorm.service';
import { ApiModule } from './api/api.module';
import { ChatModule } from './api/chat/chat.module';

const getPathConfig: string = path.join(__dirname, '..', 'env');
const envFilePath: string = getEnvPath(getPathConfig);

@Module({
  imports: [
    ConfigModule.forRoot({ envFilePath, isGlobal: true }),
    TypeOrmModule.forRootAsync({ useClass: TypeOrmConfigService }),
    ApiModule,
    ChatModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

`

Swapped ChatAuth / ChatModule imports

CodePudding user response:

come on, read the docs :D

  • ChatAuth is not a module, then there's no reason it to be listed in the imports array.
  • the page https://docs.nestjs.com/websockets/gateways shows that the gateway should be in the providers array. Again, ChatGateway is not a module, then why did you put that into imports array? the docs are pretty clear on what is the role of each option of @Module({}).
  • Related