nest.js学习笔记(七) --知识点拾遗

发布时间 2023-03-22 21:17:05作者: even_blogs

1、nestjs中引用esm插件

nestjs是使用commonjs规范进行开发,但是目前市场上很多插件是使用module的形式进行开发,所以遇到引用问题时,建议开发都绕过去,使用功能差不多的插件,但是如果遇到绕不过去的情况,那可以使用以下的方法进行引用

import { ConfigService } from '@nestjs/config';
import { Injectable } from '@nestjs/common';
import { FailException } from '@app/exceptions/fail.exception';
import { ErrorCode } from '@app/constants/error.constant';

export const importDynamic = new Function(
  'modulePath',
  'return import(modulePath)',
);

@Injectable()
export class ChatService {
  private chatGpt: any;
  public constructor(private readonly configService: ConfigService) {}

  private async initInstance(): Promise<void> {
    if (!this.chatGpt) {
      const { ChatGPTAPI } = await importDynamic('chatgpt');

      this.chatGpt = new ChatGPTAPI({
        apiKey: this.configService.get('chat.apiKey'),
      });
    }
  }

  public async getChatResponse() {
    try {
      if (!this.chatGpt) await this.initInstance();

      const res = await this.chatGpt.sendMessage('用js生成一个计算器');

      return res;
    } catch (err) {
      console.log(err);
      throw new FailException(ErrorCode.SERVER_ERROR);
    }
  }
}