标签: nestjs

如何在NestJS中创建多个Axios实例

我正在将现有的 Express 应用程序转换为 NestJS,目前我有一个配置文件,在其中为每个微服务创建多个 axios 实例:

export const writeModelApi = axios.create({
  baseURL: getWriteModelApiUrl(),
});

export const readModelApi = axios.create({
  baseURL: getReadModelApiUrl(),
});

export const configApi = axios.create({
  baseURL: getConfigApiUrl(),
});

function addCamelizeInterceptors(api: any) {
  api.interceptors.request.use(
    (config: AxiosRequestConfig): AxiosRequestConfig => {
      config.data = decamelizeKeys(config.data);

      return config;
    },
    (error: any) => {
      return Promise.reject(error);
    }
  );
  
  api.interceptors.response.use(
    (response: AxiosResponse): AxiosResponse => {
      response.data = camelizeKeys(response.data);

      return response;
    },
    (error: any) => {
      if (error.response != null) { 
        error.response.data = camelizeKeys(error.response.data);
      }

      return …
Run Code Online (Sandbox Code Playgroud)

typescript axios nestjs

1
推荐指数
1
解决办法
8097
查看次数

使用 Typeorm 查询的 forEach 中不允许使用异步函数

我正在尝试根据对象的元素执行 Typeorm 查询,但我对forEach和 异步函数有疑问。

我读过很多类似的问题,但没有人按预期为我工作。

这是我的代码片段,其中不允许等待forEach

public async runBudgetLimit(): Promise<void> {
        const contracts: ContractEntity[] = await this.contractService.getAllProjects();

        contracts.forEach((contract) => {
            const project: UserEntity = await this.userService.findOne(contract.milestoneId);
            const date: string = Time.moment().format('YYYY-MM-DD');
            const budgetUsed = this.trackService.getBillingByProject(project.contractId, date, '1000', '1000', true);
        });
    }
Run Code Online (Sandbox Code Playgroud)

这是异步 Typeorm 查询:

async findOne(id: string): Promise<UserEntity | undefined> {
        return this.userRepository.findOne(id);
}
Run Code Online (Sandbox Code Playgroud)

我不知道解决这个问题的最佳解决方案是什么,我不认为 for 循环是一个好的解决方案,但我对所有解决方案持开放态度。

foreach async.js typeorm nestjs

1
推荐指数
1
解决办法
3508
查看次数

NestJs 和 Jest:等待请求抛出 404

我目前正在尝试获取“超级测试”请求的响应对象。

\n

如果我在没有等待的情况下调用 get,我会得到一个 httpCode 200,但没有正文:

\n
import { Test, TestingModule } from '@nestjs/testing';\n\nimport { AuthModule } from './auth.module';\nimport { INestApplication } from '@nestjs/common';\nimport * as request from 'supertest';\n\ndescribe('AuthService', () => {\n   let app: INestApplication;\n   beforeAll(async () => {\n     const module: TestingModule = await Test.createTestingModule({\n  providers: [AuthModule]\n}).compile();\napp = module.createNestApplication();\nawait app.init();\n});\n\nit('should be defined', async () => {\nconst res = request(app.getHttpServer())\n  .get('/')\n  .expect(200);\n\n});\n\nafterAll(async () => {\n  app.close();\n});\n});\n
Run Code Online (Sandbox Code Playgroud)\n

Jest 给了我以下输出。但我无法引用 res.body

\n
  AuthService\n\xe2\x88\x9a should be defined (5ms)\n\nTest Suites: 1 passed, 1 total\nTests: …
Run Code Online (Sandbox Code Playgroud)

integration-testing node.js typescript jestjs nestjs

1
推荐指数
1
解决办法
4693
查看次数

如何在 NestJs 中的 Typeorm 缓存配置中重用 Redis 连接

我正在使用 Redis 在 TypeOrm 中缓存查询。

但问题是,TypeOrm 和 Redis 包正在打开单独的连接,我只想为两者重用相同的连接。

这是 typeorm 配置:

import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import { Constants } from '../utils/Constants';

export const typeOrmConfig: TypeOrmModuleOptions = {
    type: Constants.DB_TYPE,
    host: Constants.DB_HOST,
    port: Constants.DB_PORT,
    username: Constants.DB_USER_NAME,
    password: Constants.DB_PASSWORD,
    database: Constants.DB_NAME,
    entities: [ __dirname + '/../**/*.entity.{js,ts}' ],
    synchronize: true,
    logging: true,
    cache: {
        type: 'ioredis',
        duration: 60000,
        options: {
            host: 'localhost',
            password: 'swapnil',
            port: 6379
        }
    },
    extra: {
        max: 10,
        connectionTimeoutMillis: 2000
    }
};
Run Code Online (Sandbox Code Playgroud)

我正在为 redis使用@svtslv/nestjs-ioredis包:

import …
Run Code Online (Sandbox Code Playgroud)

node.js node-redis typescript typeorm nestjs

1
推荐指数
1
解决办法
1万
查看次数

通过 NestJS 将类实现注入到基于接口的抽象控制器实现中

我目前正在尝试使用 NestJS 注入进行设置,但在尝试运行服务器时遇到了错误。

我遇到的问题与我尝试将一个类注入到扩展抽象类的控制器中有关,并且我试图在构造函数中设置抽象类的属性。

控制器.ts

@Controller()
export class exampleController extends AbstractController {

  constructor(exampleClass: exampleInterface) {
    super(exampleClass);
  }

  @Get()
  getExample(): string {
    return 'Example';
  };
}
Run Code Online (Sandbox Code Playgroud)

AbstractController.ts

export abstract class AbstractController {

  private exampleClass: ExampleInterface;

  constructor(exampleClass: ExampleInterface) {
    this.exampleClass = exampleClass;
  };
Run Code Online (Sandbox Code Playgroud)

当我尝试运行我的服务器时,出现以下错误:

Error: Nest can't resolve dependencies of the ExampleController (?). Please make sure that the argument Object at index [0] is available in the AppModule context.

我已将类实现添加到 app.module 提供程序中,但即使这样,错误也会阻止我运行代码。

应用程序模块.ts

@Module({
  imports: [],
  controllers: [AppController, ExampleController],
  providers: [ExampleClass],
}) …
Run Code Online (Sandbox Code Playgroud)

node.js typescript nestjs

1
推荐指数
1
解决办法
3810
查看次数

当与 nginx 一起部署时,NestJs 在所有路由上返回 404,但在本地一切正常

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { CoreConfig } from './config.const';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { NestApplicationOptions } from '@nestjs/common';

async function bootstrap() {
  const httpOptions ={
    requestCert: false,
    rejectUnauthorized: true,
  };
  const app = await NestFactory.create(AppModule);
  const options = new DocumentBuilder()
    .addServer(`http://localhost:${CoreConfig.app.port}`)
    .setTitle('test UI/AI')
    .setDescription('UI meta service')
    .setVersion('1.0')
    .addTag('test')
    .addBearerAuth({type:'http', bearerFormat: 'authorization'})
    .build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('docs', app, document);
  app.enableCors();
  app.setGlobalPrefix('ui');
  await app.listen(CoreConfig.app.port);
}

bootstrap().then();
Run Code Online (Sandbox Code Playgroud)

当我的应用程序使用 …

nginx node.js jenkins docker nestjs

1
推荐指数
1
解决办法
2200
查看次数

NestJS - 在请求正文中接受多种 MIME 类型

我正在尝试在 HTTP API 中创建一个端点,定期从远程设备接收数据。该项目发生了技术转变,设备之前以 XML 格式报告数据,而未来的实现将转向 JSON。

我正在使用 NestJS (7.x) 和 TypeScript 编写此 API。数据将通过相同的端点 ( ) 传入POST /,并且数据格式由标头区分Content-Type

@Controller()
export class IngressController {
  constructor(private readonly ingressService: IngressService) {
  }

 /* ... */

  @Post('')
  @Header('Cache-Control', 'none')
  @HttpCode(HttpStatus.NO_CONTENT)
  public async receive(
    @Headers('Content-Type') contentType: string,
    @Req() req: any,
    @Body() body: string,
  ): Promise<InsertResponse> {
    if (IngressController.isJson(contentType)) {
      return { inserted: await this.ingressService.insertJsonString(req.body) };
    }
    if (IngressController.isXml(contentType)) {
      return { inserted: await this.ingressService.insertXmlString(req.body) };
    }
    throw new BadRequestException(contentType, 'Unsupported Content-Type'); …
Run Code Online (Sandbox Code Playgroud)

xml json nestjs

1
推荐指数
1
解决办法
4852
查看次数

使用 PartialType 扩展的 NestJS DTO 会破坏验证

在 NestJS 中给出两个 DTO 时class ADtoclass BDto class ADto extends PartialType(BDto)类型强制失败。(参数不会从字符串转换为数字,导致类验证器抛出错误)。

如果class ADto extends BDto,一切正常。

为什么使用 PartialType 不包括类型强制?

validation dto typescript class-validator nestjs

1
推荐指数
1
解决办法
3071
查看次数

在 NestJs 中使用 Socket IO 连接并发送到房间

我正在尝试使用 socketio 在 Nestjs 中创建一个简单的房间,但无法掌握房间的概念。我想要的是客户端将 id 发送到通用端点,然后服务器将该套接字加入到特定房间,然后开始从其他地方向该房间发送消息。我目前遇到的是客户加入一个名为“会议”的活动,然后收到一个假会议,但我不知道如何让多个客户加入同一个房间并同时收到相同的信息。

客户端(html)

  <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.1/socket.io.js"></script>
  <script>
    const url = 'http://localhost:4001';
    const socket = io(url); 
      socket.on('connect', function() {
        console.log('Connected');
        socket.emit('meeting', { roomId: '12345' });
      });
      socket.on('meeting', function(data) {
        console.log('you have joined the meeting: ', data);
      });
      socket.on('exception', function(data) {
        console.log('event', data);
      });
      socket.on('disconnect', function() {
        console.log('Disconnected');
      });
  </script>
Run Code Online (Sandbox Code Playgroud)

服务器(NestJS):

@WebSocketGateway(4001)
export class PackGateway implements OnGatewayConnection {

  constructor(private otherService: OtherService) {}

  @WebSocketServer()
  server: Server;

  handleConnection() {
    console.log('new connection!');
  }

  @SubscribeMessage('meeting')
  joinUserToMeeting(@MessageBody() data: any, @ConnectedSocket() client: Socket): Observable<WsResponse<any>> …
Run Code Online (Sandbox Code Playgroud)

sockets websocket node.js socket.io nestjs

1
推荐指数
1
解决办法
1万
查看次数

Nestjs如何将数据从AuthGuard传递到控制器

我有两个微服务,一个用于身份验证,另一个用于用户。我可以登录并获取令牌,并且仅在登录时才能使用受保护的路由。但是我想使用在 AuthGuard 的 canActivate 函数中获得的 userId,但我无法在控制器中访问它。最好的方法是什么?

我的授权守卫:

import { CanActivate, ExecutionContext, Inject, Logger } from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';

export class JwtAuthGuard implements CanActivate {
  constructor(
    @Inject('AUTH_CLIENT')
    private readonly client: ClientProxy,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const req = context.switchToHttp().getRequest();

    try {
      const res = await this.client
        .send(
          { role: 'auth', cmd: 'check' },
          { jwt: req.headers['authorization']?.split(' ')[1] },
        )
        .toPromise<boolean>();

      return res;
    } catch (err) {
      Logger.error(err);
      return false;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

控制器:

  @UseGuards(JwtAuthGuard) …
Run Code Online (Sandbox Code Playgroud)

security authentication api node.js nestjs

1
推荐指数
1
解决办法
3433
查看次数