graphql 入门 demo

2017-08-05

83

0

技术:graphql

运行环境:windows10 + node v8.2.1 + npm 5.3.0

demo功能:graphql淘宝前端实践 入门 demo

初始化环境(源代码)

安装node, npm

初始化服务端

npm init -f
npm install graphql express express-graphql --save

编写服务端

// The type of User is GraphQLObjectType, which has child fields
// with their own types (in this case, GraphQLString).
var userType = new graphql.GraphQLObjectType({
  name: 'User',
  fields: {
    id: { type: graphql.GraphQLString },
    name: { type: graphql.GraphQLString },
  }
});

// Define the schema with one top-level field, `user`, that
// takes an `id` argument and returns the User with that ID.
// Note that the `query` is a GraphQLObjectType, just like User.
// The `user` field, however, is a userType, which we defined above.
var schema = new graphql.GraphQLSchema({
  query: new graphql.GraphQLObjectType({
    name: 'Query',
    fields: {
      user: {
        type: userType,
        // `args` describes the arguments that the `user` query accepts
        args: {
          id: { type: graphql.GraphQLString }
        },
        // The resolve function describes how to "resolve" or fulfill
        // the incoming query.
        // In this case we use the `id` argument from above as a key
        // to get the User from `data`
        resolve: function (_, args) {
          return data[args.id];
        }
      }
    }
  })
});

express()
  .use('/graphql', graphqlHTTP({ schema: schema, pretty: true }))
  .listen(3000);

console.log('GraphQL server running on http://localhost:3000/graphql');

初始化数据源

//data.json
{
  "1": {
    "id": 1,
    "name": "Dan",
    "score": 1.23,
    "isOK": true
  },
  "2": {
    "id": 2,
    "name": "Marie",
    "score": 4.23,
    "isOK": false
  },
  "3": {
    "id": 3,
    "name": "Jessie",
    "score": 158.23,
    "isOK": false
  }
}

运行服务端,等待查询请求

node index.js

 

访问: http://localhost:3000/graphql?query={user(id:1){name%20score%20isOK}}

结果

欢迎添加微信,互相学习↑↑↑ -_-

发表评论

全部评论:0条

白老虎

programming is not only to solve problems, ways to think