NestJS依赖注入与注入依赖中的构造函数参数

时间:2021-02-04 21:01:37

标签: typescript dependency-injection jestjs nestjs

我在 NestJS 中挣扎于依赖注入,对于一个服务,该服务被注入到另一个服务中,然后由控制器使用。

Controller
    - ReturnResults <- Injected Service to get data from multiple sources
        - FileSystemReader <- Injected Service into ReturnResults. Needs
             - Configuration    <- NestJS Configuration service to return .env values

我遇到的问题是将构造函数变量从 ReturnResults 服务传递给 FileSystemReader 服务。 FileSystemReader(Configuration, string) 是一个常用函数,用于提供对许多模块的文件系统访问。 string 参数是要获取的环境设置,通常用于指定 .env 参数,用于指向文件的设置,因为不同的模块从文件系统和不同的路径读取不同的文件。

FileSystemReader 类可以工作,有测试等。

import { Inject, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

import * as fs from 'fs';
import * as path from 'path';

private Directory_:string;

@Injectable()
export class FileSystemReaderService {
    /**
     *
     * @param Configuration - ConfigService Configuration service to read the .env file
     */
    constructor(
        private readonly Configuration_:ConfigService,
        @Inject('ENV_VARIABLE') private readonly EnvPathVarName:string
    )
    {
         this.Directory_ = this.Configuration.get<string>(EnvPathVarName, './');
         ...
    }
    ...
}

然后测试文件可以通过注入 ENV_VARIABLE 来传递变量:

describe('FileReaderService', () => {
    let service: FileSystemReaderService;

    beforeEach(async () => {
        const module: TestingModule = await Test.createTestingModule({
            imports: [ ConfigModule ],
            providers: [
                ConfigService,
                { provide: 'ENV_VARIABLE', useValue: 'FILES'},
                FileSystemReaderService
            ]
        }).compile();

        service = module.get<FileSystemReaderService>(FileSystemReaderService);
    });
    ...
});

我的问题现在出现了,当我使用 FileSystemReaderService 时,注入到我的 ReturnResults 服务中。

典型的构造函数是:

constructor(
    private Configuration:ConfigService,
    @Inject('FILESYSTEM') private readonly FileSystem:FileSystemReaderService
    // This is done for the ReturnResults service to use the mock class, as I do not need to test this directly at this level.
)

我不知道如何设置变量以让 FileSystem 类使用它。如果没有依赖注入,那就是

    const FileSystemRS:FileSystemReaderService = new FileSystemReaderService(Configuration, 'FILES');

我不知道如何在构造函数的标题中执行此操作。

0 个答案:

没有答案
相关问题