我有一个 NestJS 应用程序,它充当与多个不同 API 进行通信的中心点。每一个都需要标头中不同的令牌身份验证,因此我希望根据我需要与之交互的 API 为每一个提供一个自定义 HttpService。
到目前为止,我所做的是创建一个扩展
HttpService
的服务,并将修改传出 HTTP 请求的标头。
@Injectable()
export class SharepointHttpService extends HttpService implements OnModuleInit {
constructor(private readonly httpService: HttpService) {
super();
}
public onModuleInit(): void {
this.httpService.axiosRef.interceptors.request.use((config) => {
config.headers.Authorization = `My-Token-Here`;
return config;
});
}
我制作了一个
ApiModule
,其中将包含我所有专门的 HTTP 服务
@Module({
imports: [HttpModule],
providers: [
{ provide: SharepointHttpService, useExisting: HttpService },
{ provide: OtherHttpService, useExisting: HttpService },
],
exports: [SharepointHttpService, OtherHttpService],
})
export class ApiModule {}
在我想要调用 API 的不同模块中,我像这样导入它们
@Module({
imports: [HttpModule, ApiModule],
controllers: [ExampleController],
providers: [ExampleService, SharepointHttpService, OtherHttpService],
})
export class ExampleModule {}
从那里我希望像这样注入它们,它会处理所有事情。
@Injectable()
export class ExampleService {
constructor(private readonly spHttpService: SharepointHttpService) {}
getThing() {
return this.spHttpService.get('some-endpoint');
}
}
但是我得到的是这个错误
Error: Nest can't resolve dependencies of the SharepointHttpService (?, HttpService). Please make sure that the argument "AXIOS_INSTANCE_TOKEN" at index [0] is available in the ApiModule context.
Potential solutions:
- Is ApiModule a valid NestJS module?
- If "AXIOS_INSTANCE_TOKEN" is a provider, is it part of the current ApiModule?
- If "AXIOS_INSTANCE_TOKEN" is exported from a separate @Module, is that module imported within ApiModule?
@Module({
imports: [ /* the Module containing "AXIOS_INSTANCE_TOKEN" */ ]
})
我做错了什么?这是完成我在这里尝试做的事情的最佳方法吗?
您无法扩展该
HttpService
类,因为您无法访问 @nestjs/axios
具有的内部提供程序。
在您的情况下,错误是因为您的
SharepointHttpService
证明者已声明对只有 HttpModule
具有 的提供者的依赖
相反,您可以按照我在本文中的建议增强内部 axios 实例:https://dev.to/micalevisk/nestjs-tip-how-to-inject-multiple-versions-of-the-same-provider -进入一个模块-例如许多-axios-实例-5agc
或者您可以使用工厂提供程序来创建继承自
SharepointHttpService
的 HttpService
实例(使用某种 JS 原型技巧)