Nest无法解析依赖项。

huangapple go评论87阅读模式
英文:

Nest can't resolve dependencies

问题

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
Nest无法解析依赖项。

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: [ChatAuth, ChatGateway],
  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

英文:

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
Nest无法解析依赖项。

chat.module.ts
`

import { Module } from &#39;@nestjs/common&#39;;
import { ChatAuth } from &#39;./chat.middlewares&#39;;
import { ChatGateway } from &#39;./chat.gateway&#39;;
import { AuthHelper } from &#39;../auth/auth.helper&#39;;
import { JwtStrategy } from &#39;../auth/auth.strategy&#39;;
@Module({
imports: [ChatGateway, ChatAuth],
controllers: [],
providers: [AuthHelper, JwtStrategy],
})
export class ChatModule {}

`

chat.gateway.ts
`

import {
SubscribeMessage,
WebSocketGateway,
OnGatewayInit,
WebSocketServer,
OnGatewayConnection,
OnGatewayDisconnect,
MessageBody,
} from &#39;@nestjs/websockets&#39;;
import { Logger } from &#39;@nestjs/common&#39;;
import { Socket, Server } from &#39;socket.io&#39;;
import { ChatAuth } from &#39;./chat.middlewares&#39;;
@WebSocketGateway(7000)
export class ChatGateway
implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
@WebSocketServer() server: Server;
private chatAuthHelper: ChatAuth;
private logger: Logger = new Logger(&#39;ChatGateway&#39;);
constructor(chatAuthHelper: ChatAuth) {
this.chatAuthHelper = chatAuthHelper;
}
@SubscribeMessage(&#39;msgToServer&#39;)
handleMessage(client: Socket, payload: string): void {
console.log(payload);
this.server.emit(&#39;msgToClient&#39;, payload);
}
@SubscribeMessage(&#39;events&#39;)
handleEvent(@MessageBody() data: string): void {
const parsed = JSON.parse(JSON.stringify(data));
parsed.msg = parsed.msg + &#39; 3&#39;;
this.server.emit(&#39;onMessage&#39;, {
msg: &#39;New message&#39;,
content: parsed.msg,
});
}
afterInit(server: Server) {
this.logger.log(&#39;Init&#39;);
}
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 &#39;@nestjs/common&#39;;
import { AuthHelper } from &#39;../auth/auth.helper&#39;;
@Injectable()
export class ChatAuth implements NestMiddleware {
private helper: AuthHelper;
constructor(helper: AuthHelper) {
this.helper = helper;
}
public async use(token): Promise&lt;object&gt; {
const currentToken = token.split(&#39; &#39;)[1];
const user = await this.helper.validate(currentToken);
console.log(JSON.stringify(user));
return user;
}
}

`

app.module.ts
`

import { Module } from &#39;@nestjs/common&#39;;
import * as path from &#39;path&#39;;
import { ConfigModule } from &#39;@nestjs/config&#39;;
import { TypeOrmModule } from &#39;@nestjs/typeorm&#39;;
import { AppController } from &#39;./app.controller&#39;;
import { AppService } from &#39;./app.service&#39;;
import { getEnvPath } from &#39;./common/helper/env.helper&#39;;
import { TypeOrmConfigService } from &#39;./shared/typeorm/typeorm.service&#39;;
import { ApiModule } from &#39;./api/api.module&#39;;
import { ChatModule } from &#39;./api/chat/chat.module&#39;;
const getPathConfig: string = path.join(__dirname, &#39;..&#39;, &#39;env&#39;);
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

答案1

得分: 1

来吧,阅读文档 Nest无法解析依赖项。

  • ChatAuth 不是一个模块,所以没有理由将其列在 imports 数组中。
  • 页面 https://docs.nestjs.com/websockets/gateways 显示网关应该在 providers 数组中。再次强调,ChatGateway 不是一个模块,那么为什么将其放入 imports 数组中呢?文档对 @Module({}) 的每个选项的角色都非常明确。
英文:

come on, read the docs Nest无法解析依赖项。

  • 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({}).

huangapple
  • 本文由 发表于 2023年1月3日 21:12:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/74993839.html
  • nestjs
  • node.js
  • socket.io
  • typescript
  • websocket

在Nunjucks模板中访问数组在 :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定