带接口的 Nestjs 提供程序

Nestjs Provider with interface

我知道 Nestjs 喜欢 Angular,不允许使用接口作为提供者。我该如何解决这个问题?

我想作为提供者维护接口,以便更简单地测试它,或者最终更改数据库,例如 UserMongoDb。数据库对象在单独的库中,我无法将它们更改为 abstract 类.

    interface UserDatabase {
        create();
        read();
    }

    class UserOracleDb implements UserDatabase {
        create()
        {
            throw new Error("Method not implemented.");
        }
        read()
        {
            throw new Error("Method not implemented.");
        }       
    }

    @Injectable()
    export class UserRepository {
        constructor(private repository: UserDatabase)
    }


    // ... module.ts
    {
        providers: [
            {
                provide: Database,// Wants a class not an interface
                useValue: new UserOracleDb('USER_TABLE')
            }
        ]
    }

阅读文档后,答案是使用此处描述的方法https://docs.nestjs.com/fundamentals/custom-providers#non-class-based-provider-tokens

就我而言:

    @Injectable()
    export class UserRepository {
        constructor(@Inject('USER_REPO') private repository: UserDatabase)
    }

    {
        providers: [
            {
                provide: 'USER_REPO',
                useValue: new UserOracleDb('USER_TABLE')
            }
        ]
    }