【问题标题】:Emit deprecation warnings with Apollo client使用 Apollo 客户端发出弃用警告
【发布时间】:2018-04-13 21:18:32
【问题描述】:

背景

我们正在开发一个相当大的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 中间件中完成?
  • 我也对执行此操作的某种实现或工具感兴趣 :)
  • @Striped 在下面添加了解决方案。

标签: graphql apollo apollo-client


【解决方案1】:

所以两年后回到 GraphQL,我才发现 schema directives can be customized(现在?)。所以这里有一个解决方案:

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}`)
})

这适用于服务器而不是客户端。它应该打印在客户端上追踪错误查询所需的所有信息。从维护的角度来看,将它放在服务器日志中似乎更可取。

【讨论】:

    猜你喜欢
    • 2020-09-13
    • 2019-03-27
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 2018-07-18
    • 2020-04-27
    • 2017-12-08
    • 2019-07-27
    相关资源
    最近更新 更多