GraphQL示例代码

2019-07-24 23:13  2829人阅读  评论 (0)

查询user 关联blog

var express = require('express');
var graphqlHTTP = require('express-graphql');
var { 
  GraphQLSchema, 
  GraphQLObjectType, 
  GraphQLID, 
  GraphQLString, 
  GraphQLInt 
} = require('graphql');

var Blog = new GraphQLObjectType({
  name: "Blog",
  fields: {
    id: { type: GraphQLID },
    title: { type: GraphQLString },
    content: { type: GraphQLString },
    created_time: { type: GraphQLInt }
  }
})

var User = new GraphQLObjectType({
  name: "User",
  fields: {
    id: { type: GraphQLID },
    username: { type: GraphQLString },
    password: { type: GraphQLString },
    blog: {
      type: Blog,
      resolve(parent, args) {
        console.log(parent, args)
        return {
          id: parent.id,
          title: "title" + parent.id,
          content: "content" + parent.id,
          created_time: parent.id * 100
        }
      }
    }
  }
})

var Query = new GraphQLObjectType({
  name: "Query",
  fields: {
    user: {
      type: User,
      args: {
        id: { type: GraphQLID }
      },
      resolve(parent, args) {
        console.log(parent, args)
        return {
          id: args.id,
          username: "admin" + args.id,
          password: "123456" + args.id,
        }
      }
    }
  }
})

var schema = new GraphQLSchema({
  query: Query
})

var app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true,
}));
app.listen(4000, () => console.log('Now browse to localhost:4000/graphql'));
豫ICP备09035262号-1