nestjs+gql路由冲突/覆盖

tjrkku2a  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(385)

大家好,我的nestjs应用程序中存在冲突/覆盖问题。
那么,问题是什么:
我有一个解析器

  1. @Resolver('ResolverA')
  2. export class SomePageResolver {
  3. constructor(private readonly someService: someService) {
  4. }
  5. @Query(() => someType)
  6. theThingThatMessesUpStuff(
  7. @Args('params') params: HttpParamsInput,
  8. @Context(TokenPipe) authorization: string,
  9. ): Observable<ActionSetsPageType> {
  10. return this.someService.doSomething(params, authorization)
  11. }
  12. }

和解析器b

  1. @Resolver('ResolverB')
  2. export class SomePageResolver{
  3. constructor(private readonly someService: someService) {
  4. }
  5. @Query(() => someOtherType)
  6. theThingThatMessesUpStuff(
  7. @Args('params') params: HttpParamsInput,
  8. @Context(TokenPipe) authorization: string,
  9. ): Observable<ActionSetsPageType> {
  10. return this.someService.doSomethingElse(params, authorization)
  11. }
  12. }

分别地 Resolver AModule AResolver BModule B .
根据我拥有的版本,两者都有可能 Module AModule B 在单个模块(单亲模块)中导入,这会导致覆盖问题。问题的实质是,当两个模块都是构建的一部分时,如果客户机查询 theThingThatMessesUpStuff 它将使用最后导入的模块进行查询

  1. // some code
  2. @Module({
  3. imports: [
  4. // some imports
  5. ModuleB,
  6. ModuleA
  7. ]
  8. })
  9. // some more code

如果使用上面的示例配置,则每当客户端尝试查询 theThingThatMessesUpStuff 字段,查询将由内部的实现解决 ModuleA ,其中对于某些功能(在与此构建相关的前端内部),客户机希望在内部实现 ModuleB 现在回到主要问题,是否有一种不需要太多人参与的方法来创建一个验证,以保证在nestjs应用程序的范围内只存在唯一的gql查询。

t3psigkw

t3psigkw1#

到目前为止,我已经找到了两种解决方案:
以某种方式在项目的所有团队和人员中实施一种命名约定,以某种前缀的形式,只要每个团队成员都知道并保持警惕,这种命名约定就会起作用。
创建decorator函数并修饰所有查询

  1. const registered = {};
  2. export const uniqueKey = () => {
  3. return function(_target: any, propertyKey: string) {
  4. if (registered[propertyKey]) {
  5. console.error(`${propertyKey} already in used`);
  6. throw new Error(`Resolver name already in use`);
  7. } else {
  8. registered[propertyKey] = true;
  9. }
  10. };
  11. };

而这个东西也会这样使用

  1. @Resolver('ResolverA')
  2. export class SomePageResolver {
  3. constructor(private readonly someService: someService) {
  4. }
  5. @uniqueKey()
  6. @Query(() => someType)
  7. theThingThatMessesUpStuff(
  8. @Args('params') params: HttpParamsInput,
  9. @Context(TokenPipe) authorization: string,
  10. ): Observable<ActionSetsPageType> {
  11. return this.someService.doSomething(params, authorization)
  12. }
  13. }

有了这个解决方案,开发人员应该再次提高警惕,在任何地方都使用decorator,而且这个decorator应该应用于整个代码库,以实现一致性(这是一项非常不愉快的任务)。

展开查看全部

相关问题