GraphQL buildSchema vs GraphQLObjectType

Mic*_*uce 9 schema resolver object-type graphql

我浏览了GraphQL的对象类型教程,然后阅读了文档的构造类型部分.我通过创建一个简单的做了一个类似的风格审判case convention converter.为什么?学习 :)

转换为使用时GraphQLObjectType,我希望得到相同的结果buildSchema.

  1. 为什么buildSchema使用type CaseConventions但在使用GraphQLObjectType时没有设置type?我在这里做错了吗?
  2. 我是否以任何令人担忧的问题实施此措施?
  3. 我应该像使用版本一样使用版本的rootValue对象吗?GraphQLObjectTypebuildQuery

感谢您的耐心和帮助.


两个版本都使用此对象:

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; 
Run Code Online (Sandbox Code Playgroud)


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
}));
Run Code Online (Sandbox Code Playgroud)


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
}));
Run Code Online (Sandbox Code Playgroud)

kim*_*254 9

我会尽力满意地回答你的问题.

  1. 为什么buildSchema使用CaseConventions类型但是在使用GraphQLObjectType时它没有设置类型?我在这里做错了什么

    它们是两种不同的实施方式.使用buildSchemagraphQL模式语言GraphQLSchema而不使用模式语言时,它以编程方式创建模式.

  2. 我是否以任何令人担忧的问题实施此措施?

  3. 我应该像使用buildQuery版本一样使用带有GraphQLObjectType版本的rootValue对象吗?

    不,在buildSchema中,根提供了解析器,而在使用GraphQLSchema时,根级解析器是在Query和Mutation类型而不是根对象上实现的.