[英]Set resolver on individual field with GraphQL
I would like to set a resolver, on an individual field that returns a string. 我想在返回字符串的单个字段上设置解析器。
For this example. 对于这个例子。 I want to take the
title
attribute, and make it .toUpperCase
我想将
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
}
}
Here is the solution: 解决方法如下:
const resolvers = {
Product: {
title: product => {
return product.title.toUpperCase();
}
},
Query: {
products: () => [{title:'foo'}]
}
};
typeDefs: 类型定义:
type Product {
title: String!
}
type Query {
products: [Product]
}
Another way is to use custom directive like "@upperCase", but it's too complex for this. 另一种方法是使用自定义指令,例如“ @upperCase”,但是这样做太复杂了。
update directive way 更新指令方式
@uppercase
directive implementation: @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
: 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
: schema
:
const schema: GraphQLSchema = makeExecutableSchema({
typeDefs,
resolvers,
schemaDirectives: {
deprecated: DeprecatedDirective,
uppercase: UppercaseDirective
}
});
Here is source code: https://github.com/mrdulin/apollo-server-express-starter/tree/master/src/custom-directive 这是源代码: https : //github.com/mrdulin/apollo-server-express-starter/tree/master/src/custom-directive
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.