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

Javascript 使用GraphQL在单个字段上设置解析器,javascript,graphql,Javascript,Graphql,我想在返回字符串的单个字段上设置一个解析器 对于这个例子。我想获取title属性,并使其成为.toUpperCase 模式 分解器 以下是解决方案: const resolvers = { Product: { title: product => { return product.title.toUpperCase(); } }, Query: { products: () => [{title:'foo'}] } }; type

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

对于这个例子。我想获取title属性,并使其成为.toUpperCase

模式 分解器 以下是解决方案:

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

type Product {
  title: String!
}
type Query {
  products: [Product]
}
另一种方法是使用自定义指令,如@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 };
模式:


以下是源代码:

谢谢,但这似乎不对。每次都可以使用title.toUpperCase。我想给它传递一个参数,以确定它是否应该。啊,我看到了棘手的部分——将其称为模式类型本身。奇怪的是,我可以为产品命名任何我想要的东西——但不能查询。我现在明白了。Thanks@Ycon更新graphql指令方式谢谢-对于这样的用例,指令方式似乎有点冗长,但很好知道
type Product {
  title: String!
}
type Query {
  products: [Product]
}
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 };
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]!
  }
`;
const schema: GraphQLSchema = makeExecutableSchema({
  typeDefs,
  resolvers,
  schemaDirectives: {
    deprecated: DeprecatedDirective,
    uppercase: UppercaseDirective
  }
});