自定义指令
这是 GraphQL 库 7 版本的文档。对于长期支持 (LTS) 版本 5,请参阅GraphQL 库 5 LTS 版本。 |
截至 @graphql-tools
版本 8,定义和应用自定义指令的机制已显著改变,这在 Neo4j GraphQL 库中也有所体现。
要理解这些变化,请考虑以下示例。它通过实现一个字段指令来将字段值转换为大写,使用以下定义:
directive @uppercase on FIELD_DEFINITION
根据 @graphql-tools
文档,将创建一个函数,该函数同时返回定义和提供行为的转换器。
function upperDirective(directiveName: string) {
return {
upperDirectiveTypeDefs: `directive @${directiveName} on FIELD_DEFINITION`,
upperDirectiveTransformer: (schema: GraphQLSchema) =>
mapSchema(schema, {
[MapperKind.OBJECT_FIELD]: (fieldConfig) => {
const fieldDirective = getDirective(schema, fieldConfig, directiveName)?.[0];
if (fieldDirective) {
const { resolve = defaultFieldResolver } = fieldConfig;
fieldConfig.resolve = async (source, args, context, info) => {
const result = await resolve(source, args, context, info);
if (typeof result === "string") {
return result.toUpperCase();
}
return result;
};
}
return fieldConfig;
},
}),
};
}
调用该函数时,将返回指令的类型定义和转换器。
const { upperDirectiveTypeDefs, upperDirectiveTransformer } = upperDirective("uppercase");
在构造 Neo4jGraphQL
实例时,指令定义可以与其他类型定义一起传递到 typeDefs
数组中。
const neoSchema = new Neo4jGraphQL({
typeDefs: [
upperDirectiveTypeDefs,
`#graphql
type Movie @node {
name: String @uppercase
}
`,
],
driver,
});
最后,必须使用从指令函数返回的转换器来转换 Neo4j GraphQL 模式。
const schema = upperDirectiveTransformer(await neoSchema.getSchema());
请注意,此 schema
对象是 GraphQLSchema
的一个实例,可在任何 GraphQL 工具中使用,例如在 Apollo Server 中。