Node.js 服务端实践之 GraphQL 初探--基于windows的演练

原文地址: http://taobaofed.org/blog/2015/11/26/graphql-basics-server-implementation/
最近有点时间来看下nodejs和graphQL,于是看了下官网并自己手动尝试了一下。遇到了一些问题,在此把我遇到的问题记录下,便于帮助大家更好的阅读.

1. 使用 Node.js 实现 GraphQL 服务器

我们先按照官方文档搭建一个 GraphQL 服务器:
Node version: 8.11.1

$ mkdir graphql-intro && cd ./graphql-intro
$ npm install 
$ npm install express --save
$ npm install babel --save

index.js 的内容如下:

//index.js
//require `babel/register` to handle JavaScript code

require('babel/register');
require('./server.js');

server.js 的内容如下:

//server.js
import express from 'express';

let app = express();
let PORT = 3000;

app.post('/graphql', (req, res) => {
  res.send('Hello!');
});

let server = app.listen(PORT, function() {
  let host = server.address().address;
  let port = server.address().port;

  console.log('GraphQL listening at http://%s:%s', host, port);
});

然后执行代码: nodemon index.js:

通常会报import错误。原因是import是es6的命令。需要手动转下。
你运行如下命令

npm install --save-dev babel-cli
npm install --save-dev babel-preset-es2015Copy

.babelrc 的内容如下,把此文件拷贝到和package.json同一目录下。
{
“presets”: [“es2015”]
}
这样你的第一个graphql就运行起来了。

里面还有一些问题如没有ItemService等问题。我直接列出可以运行的版本了。大家自己对比学习吧。
//server.js

import express from 'express';
import ItemSchema from './schema';

import { graphql } from 'graphql';
import bodyParser from 'body-parser';

let app = express();
let PORT = 3000;

//Parse post content as text
app.use(bodyParser.text({ type: 'application/graphql' }));

app.post('/graphql', (req, res) => {
  //GraphQL executor
  graphql(ItemSchema, req.body)
  .then((result) => {
    res.send(JSON.stringify(result, null, 2));
  })
});

let server = app.listen(PORT, function() {
  let host = server.address().address;
  let port = server.address().port;

  console.log('GraphQL listening at http://%s:%s', host, port);
});

//schema.js

import {
  GraphQLObjectType,
  GraphQLSchema,
  GraphQLInt,
  GraphQLString
} from 'graphql';

let count = 0;
let id = 0;

var schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
      count: {
        type: GraphQLInt,
        //Add description
        description: 'The count!',
        resolve: function() {
          return count;
        }
      }
    }
  }),
  //Note:this is the newly added mutation query
  mutation: new GraphQLObjectType({
    name: 'RootMutationType',
    fields: {
      updateCount: {
        type: GraphQLInt,
        description: 'Update the count',
        resolve: function() {
          count += 1;
          return count;
        }
      }
    }
  })
});

var ItemType =  new GraphQLObjectType({
  name: "item",
  description: "item",
  fields: {
    id: {
      type: GraphQLString,
      description: "item id"
    },
    title: {
      type: GraphQLString,
      description: "item title"
    },
    price: {
      type: GraphQLString,
      description: "item price",
      resolve: function(root, param, context) {
        return (root.price/100).toFixed(2);
      }
    },
    pic: {
      type: GraphQLString,
      description: "item pic url"
    }
  }
});

var ItemService=function(id)
{
    var items = [
      {id: '1', title: 'Item 1',price:'100', pic:'11'},
      {id: '2', title: 'Item 2',price:'100', pic:'11'},
      {id: '3', title: 'Item 3',price:'100', pic:'11'},
      {id: '4', title: 'Item 4',price:'100', pic:'11'},
      {id: '5', title: 'Item 5',price:'100', pic:'11'}
    ];
    return items[id];       
}

var ItemSchema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: "ItemQuery",
    description: "query item",
    fields: {
      item: {
        type: ItemType,
        description: "item",
        args: {
          id: {
            type: GraphQLInt,
            required: true    //itemId required for query
          }
        },
        resolve: function(root, obj, ctx) {
         return ItemService(obj['id']);
        //return 11;
        }
      }
    }
  }),
   //Note:this is the newly added mutation query
  mutation: new GraphQLObjectType({
    name: 'RootMutationType',
    fields: {
      updateCount: {
        type: GraphQLInt,
        description: 'Update the count',
        resolve: function() {
          count += 1;
          return count;
        }
      }
    }
  })
});
export default ItemSchema;

你可能感兴趣的:(Node.js 服务端实践之 GraphQL 初探--基于windows的演练)