美文网首页
Constructing Types

Constructing Types

作者: 紫雨杰 | 来源:发表于2020-07-16 20:00 被阅读0次

    一、使用GraphQLObjectType 定义type(类型)


    image.png

    二、使用GraphQLObjectType 定义Query(查询)


    image.png
    三、创建schema

    var schema = new graphql.GraphQLSchema({query: queryType});

    const express = require('express');
    const graphql = require('graphql');
    const {graphqlHTTP} = require('express-graphql');
    
    
    // 定义Schema,  查询方法和返回值类型
    //const schema = buildSchema(`
    //  type Account {
    //      name: String
    //      age: Int
    //      sex: String
    //      department: String
    //      salary(city: String): Int
    //  }
    //  type Query {
    //    getClassMates(classNo: Int!): [String]
    //    account(username: String): Account
    //  }
    //`)
    
    const AccountType = new graphql.GraphQLObjectType({
      name: 'Account',
      fields: {
        name: {type: graphql.GraphQLString},
        age: {type: graphql.GraphQLInt},
        sex: {type: graphql.GraphQLString},
        department: {type: graphql.GraphQLString}
      }
    });
    
    const queryType = new graphql.GraphQLObjectType({
      name: 'Query',
      fields: {
        account: {
          type: AccountType,
          args: {
            username: {type: graphql.GraphQLString}
          },
          resolve: function(_, {username}) {
            const name = username;
            const age = 19;
            const sex = '男';
            const department = '开发部';
            return {
              name,
              age,
              sex,
              department
            }
          }
        }
      }
    });
    
    const schema = new graphql.GraphQLSchema({query: queryType}); 
    
    const app = express();
    
    app.use('/graphql', graphqlHTTP({
        schema: schema,
        graphiql: true
    }))
    
    app.listen(3000);
    

    相关文章

      网友评论

          本文标题:Constructing Types

          本文链接:https://www.haomeiwen.com/subject/ivrmhktx.html