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

时间:2018-08-13 23:21:43

标签: javascript graphql

我想在返回字符串的单个字段上设置解析器。

对于此示例。我想使用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 个答案:

答案 0 :(得分:1)

这是解决方案:

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

typeDefs:

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