我们正在开展一个相当大的Apollo项目。我们api的一个非常简化的版本如下:
type Operation {
foo: String
activity: Activity
}
type Activity {
bar: String
# Lots of fields here ...
}
我们已经意识到拆分Operation
和Activity
没有任何好处,并增加了复杂性。我们想合并它们。但是在代码库中有许多假设这种结构的查询。为了逐步过渡,我们添加@deprecated
指令:
type Operation {
foo: String
bar: String
activity: Activity @deprecated
}
type Activity {
bar: String @deprecated(reason: "Use Operation.bar instead")
# Lots of fields here ...
}
是否有某种方法可以强调未来的弃用?最好是在(在测试环境中)运行使用不推荐使用的字段的查询时在浏览器控制台中打印警告?
答案 0 :(得分:2)
因此,两年后回到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}`)
})
这适用于服务器而不是客户端。但是,它应打印出在客户端上跟踪错误查询所需的所有信息。从维护的角度来看,将其存储在服务器日志中似乎是可取的。