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

wor*_*shi 6 apollo graphql apollo-client

背景

我们正在做一个相当大的Apollo项目。我们的api的简化版本如下所示:

type Operation {
    foo: String
    activity: Activity
}

type Activity {
    bar: String
    # Lots of fields here ...
}
Run Code Online (Sandbox Code Playgroud)

我们已经意识到分裂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 ...
}
Run Code Online (Sandbox Code Playgroud)

实际问题

有什么方法可以突出显示将来的弃用?最好通过在(在测试环境中)运行使用已弃用字段的查询时在浏览器控制台中打印警告?

wor*_*shi 3

GraphQL模式指令 可以定制。因此,下面是一个在服务器上打印警告的解决方案(Edit 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}`)
})

Run Code Online (Sandbox Code Playgroud)