【发布时间】:2017-11-29 14:58:39
【问题描述】:
我浏览了 GraphQL 的 Object Types 教程,然后阅读了文档的 Constructing Types 部分。我通过创建一个简单的case convention converter 进行了类似的风格试验。为什么?学习:)
当转换为使用GraphQLObjectType 时,我想要与buildSchema 相同的结果。
- 为什么
buildSchema使用type CaseConventions而使用GraphQLObjectType时却没有设置为type?我在这里做错了吗? - 我实施此操作时是否存在任何令人担忧的问题?
- 我是否应该像使用
buildQuery版本一样使用带有GraphQLObjectType版本的rootValue对象?
感谢您的耐心和帮助。
两个版本都使用这个对象:
class CaseConventions {
constructor(text) {
this.text = text;
this.lowerCase = String.prototype.toLowerCase;
this.upperCase = String.prototype.toUpperCase;
}
splitTargetInput(caseOption) {
if(caseOption)
return caseOption.call(this.text).split(' ');
return this.text.split(' ');
}
cssCase() {
const wordList = this.splitTargetInput(this.lowerCase);
return wordList.join('-');
}
constCase() {
const wordList = this.splitTargetInput(this.upperCase);
return wordList.join('_');
}
}
module.exports = CaseConventions;
buildSchema 版本:
const schema = new buildSchema(`
type CaseConventions {
cssCase: String
constCase: String
}
type Query {
convertCase(textToConvert: String!): CaseConventions
}
`);
const root = {
convertCase: ({ textToConvert }) => {
return new CaseConventions(textToConvert);
}
};
app.use('/graphql', GraphQLHTTP({
graphiql: true,
rootValue: root,
schema
}));
GraphQLObjectType 版本:
const QueryType = new GraphQLObjectType({
name: 'Query',
fields: {
cssCase: {
type: GraphQLString,
args: { textToConvert: { type: GraphQLString } },
resolve(parentValue) {
return parentValue.cssCase();
}
},
constCase: {
type: GraphQLString,
args: { textToConvert: { type: GraphQLString } },
resolve(parentValue) {
return parentValue.constCase()
}
}
}
});
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
convertCase: {
type: QueryType,
args: { textToConvert: { type: GraphQLString } },
resolve(p, { textToConvert }) {
return new CaseConventions(textToConvert);
}
}
}
});
const schema = new GraphQLSchema({
query: RootQuery
});
app.use('/graphql', GraphQLHTTP({
graphiql: true,
schema
}));
【问题讨论】:
标签: schema graphql resolver object-type