代码之家  ›  专栏  ›  技术社区  ›  Ycon

使用GraphQL在单个字段上设置解析器

  •  0
  • Ycon  · 技术社区  · 7 年前

    对于这个例子。我想把 title 属性,并使其 .toUpperCase

    type Product {
      title(uppercase:Boolean!): String!
    }
    type Query {
      products: [Product]
    }
    

    分解器

    Query: {
        products: () => [{title:'foo'}],
        products.title: (stringToRtn, { action }) => {
        return action ? stringToRtn.toUpperCase : stringToRtn
      }
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Lin Du Correcter    6 年前

    以下是解决方案:

    const resolvers = {
      Product: {
        title: product => {
          return product.title.toUpperCase();
        }
      },
      Query: {
        products: () => [{title:'foo'}]
      }
    };
    

    type Product {
      title: String!
    }
    type Query {
      products: [Product]
    }
    

    另一种方法是使用像“@upperCase”这样的自定义指令,但这太复杂了。

    更新指令方式

    @uppercase 指令执行:

    import { SchemaDirectiveVisitor } from 'graphql-tools';
    import { GraphQLField, defaultFieldResolver } from 'graphql';
    
    class UppercaseDirective extends SchemaDirectiveVisitor {
      public visitFieldDefinition(field: GraphQLField<any, any>) {
        const { resolve = defaultFieldResolver } = field;
        field.resolve = async function resolver(...args) {
          const result = resolve.apply(this, args);
          if (typeof result === 'string') {
            return result.toUpperCase();
          }
          return result;
        };
      }
    }
    
    export { UppercaseDirective };
    

    typeDefs.ts

    const typeDefs: string = `
      enum Status {
        SOLD_OUT
        NO_STOCK
        OUT_OF_DATE @deprecated(reason: "This value is deprecated")
      }
    
      type Book {
        id: ID!
        title: String @uppercase
        author: String
        status: Status
        name: String @deprecated(reason: "Use title instead")
      }
    
      type Query {
        books: [Book]!
        bookByStatus(status: Status!): [Book]!
      }
    `;
    

    schema :

    const schema: GraphQLSchema = makeExecutableSchema({
      typeDefs,
      resolvers,
      schemaDirectives: {
        deprecated: DeprecatedDirective,
        uppercase: UppercaseDirective
      }
    });
    

    以下是源代码: https://github.com/mrdulin/apollo-server-express-starter/tree/master/src/custom-directive

    推荐文章