Я не могу ввести класс по идентификатору для интерфейсов - PullRequest
0 голосов
/ 30 марта 2020

Я думаю, что это трудно читать, потому что я использую функцию перевода для написания предложений, извините.

Я пытаюсь внедрить поставщика на основе интерфейса. Ниже приведен мой код.

storage-base.interface.ts

export interface IStorageBase {
  upload(fileName: string): Promise<string>;
  deleteLocalFile(fileName: string): Promise<void>;
}

blob.service.ts

import { Injectable } from '@nestjs/common';
import { BlobServiceClient, ContainerClient } from '@azure/storage-blob';
import { IStorageBase } from './storage-base.interface';

type BlobDependencies = {
  connectionString: string;
  containerName: string;
};

@Injectable()
export class BlobService implements IStorageBase {
  private readonly blobServiceClient: BlobServiceClient;
  private readonly containerClient: ContainerClient;

  constructor(blobDependencies: BlobDependencies) {
    //Some kind of processing
  }

  upload(filename: string): Promise<string> {
    //Some kind of processing
  }

  deleteLocalFile(filename: string): Promise<void> {
    //Some kind of processing
  }

  private getAbsolutePath(filename: string): string {
    //Some kind of processing
  }
}

core.module.ts

import { Module } from '@nestjs/common';
import { BlobService } from './blob.service';

const blobServiceProvider = { provide: 'IStorageBase', useClass: BlobService };

@Module({
  providers: [blobServiceProvider],
  exports: [blobServiceProvider],
})
export class CoreModule {}

Класс Blob реализует интерфейс IStorageBase. И CoreModule делает поставщиков на основе IStoraegBase доступными для других модулей.

пример:

video-cut-out.module.ts

import { Module } from '@nestjs/common';
import { VideoCutOutService } from './video-cut-out.service';
import { VideoCutOutController } from './video-cut-out.controller';
import { CoreModule } from '../core/core.module';

@Module({
  imports: [CoreModule],
  providers: [VideoCutOutService],
  controllers: [VideoCutOutController],
  exports: [],
})
export class VideoCutOutModule {}

video-cut-out.service.ts

import { Injectable, Inject } from '@nestjs/common';
import { VideoCutOutRequest, VideoCutOutResponse } from './video-cut-out.model';
import { IStorageBase } from '../core/storage-base.interface';

@Injectable()
export class VideoCutOutService {
  constructor(@Inject('IStorageBase') private _blob: IStorageBase) {}
  async executeAsync(
    videoCutOutRequest: VideoCutOutRequest,
  ): Promise<VideoCutOutResponse> {
    //Some kind of processing
  }
}

Однако, когда это выполняется, выдается следующая ошибка.

[Nest] 18352   - 2020-03-30 17:04:12   [ExceptionHandler] Nest can't resolve dependencies of the IStorageBase (?). Please make sure that the argument Object at index [0] is available in the CoreModule context.

Potential solutions:
- If Object is a provider, is it part of the current CoreModule?
- If Object is exported from a separate @Module, is that module imported within CoreModule?
  @Module({
    imports: [ /* the Module containing Object */ ]
  })
 +47ms

Я думаю, что интерфейс не может быть введен в «поставщики» или «импорт» модуля Decorator. Как я могу устранить вышеуказанную ошибку и нормально запустить программу?

спасибо.

1 Ответ

0 голосов
/ 30 марта 2020

У Nest возникла проблема, потому что в вашем BlobService есть зависимости от BlobDependencies, но в вашем CoreModule их нет. Наряду с этим, поскольку это пользовательский тип, а не класс, он конвертируется в object во время выполнения, поэтому Nest выдает ошибку Nest can't resolve dependencies of the IStorageBase (?). Please make sure that the argument Object at index [0] is available in the CoreModule context.. Здесь важно отметить, что речь идет о IStorageBase в контексте CoreModule, что означает, что CoreModule - это то, где ошибка. Чтобы это исправить, предоставьте некую зависимость для внедрения в Nest и обязательно добавьте декоратор @Inject(), поскольку Nest не сможет вводить в общем случае для Object

...