自定义指令

这是 GraphQL Library 7 版本的文档。对于长期支持 (LTS) 版本 5,请参考 GraphQL Library 5 LTS 版本

自版本 8 起,@graphql-tools 的自定义指令定义和应用机制已发生显著变化,这一点也体现在 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。