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

对于这个例子。我想采用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
  }
}

最佳答案

解决方法如下:

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

09-27 21:48