使用Apollo客户端发出弃用警告

10

背景

我们正在开展一个相当大的Apollo项目。我们 API 的一个非常简化版本如下:

type Operation {
    foo: String
    activity: Activity
}

type Activity {
    bar: String
    # Lots of fields here ...
}

我们意识到将OperationActivity分开没有任何好处,反而增加了复杂性。因此我们想要将它们合并。但是在代码库中有很多查询都假定了这种结构。为了使转换逐步进行,我们添加了@deprecated指令:

type Operation {
    foo: String
    bar: String
    activity: Activity @deprecated
}

type Activity {
    bar: String @deprecated(reason: "Use Operation.bar instead")
    # Lots of fields here ...
}

实际问题

有没有一种方法可以在今后突出显示这些弃用项?最好是在(测试环境中)运行使用已弃用字段的查询时,在浏览器控制台中打印警告信息。


我在考虑是否可以通过 apollo-client 中间件来实现? - worldsayshi
我也对某种实现或工具感兴趣,可以做到这一点 :) - Striped
1
@Striped 在下面添加了解决方案。 - worldsayshi
有人构建了一个插件。 (https://github.com/alexxiyang/apollo-deprecated-highlight) - worldsayshi
1个回答

3

GraphQL 模式指令 可以自定义。下面是一个解决方案,在服务器上打印警告 (编辑于2023年:这里有一个插件,可以将警告传播到客户端):

import { SchemaDirectiveVisitor } from "graphql-tools"
import { defaultFieldResolver } from "graphql"
import { ApolloServer } from "apollo-server"


class DeprecatedDirective extends SchemaDirectiveVisitor {
  public visitFieldDefinition(field ) {
    field.isDeprecated = true
    field.deprecationReason = this.args.reason

    const { resolve = defaultFieldResolver, } = field
    field.resolve = async function (...args) {
      const [_,__,___,info,] = args
      const { operation, } = info
      const queryName = operation.name.value
      // eslint-disable-next-line no-console
      console.warn(
      `Deprecation Warning:
        Query [${queryName}] used field [${field.name}]
        Deprecation reason: [${field.deprecationReason}]`)
      return resolve.apply(this, args)
    }
  }

  public visitEnumValue(value) {
    value.isDeprecated = true
    value.deprecationReason = this.args.reason
  }
}

new ApolloServer({
  typeDefs,
  resolvers,
  schemaDirectives: {
    deprecated: DeprecatedDirective,
  },
}).listen().then(({ url, }) => {
  console.log(`  Server ready at ${url}`)
})


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接