GraphQL 渐进学习 01-GraphQL-快速上手

316 阅读1分钟

graphql-quick-start

01-GraphQL-快速上手

目标

  • 创建一个 Node Express GraphQL server
  • 采用可视化 GraphiQL IDE 进行测试

代码

创建一个 node 项目

mkdir graphql-example
cd graphql-example
npm init

安装依赖包

npm install --save apollo-server-express graphql-tools graphql express body-parser

运行官方示例

为了突出关键点,省略完整代码

完整代码移步 quick-start.js

1 创建文件 quick-start.js

vi quick-start.js

2 定义数据结构

// GraphQL schema
const typeDefs = `
  type Query { books: [Book] }
  type Book { title: String, author: String }
`

3 定义处理函数

// resolvers
const resolvers = {
  Query: {books: () => books}
}

4 合并定义

const schema = makeExecutableSchema({
  typeDefs,
  resolvers
})

5 路由 GraphQL 数据服务

app.use('/graphql', bodyParser.json(), graphqlExpress({schema}))

6 路由 GraphIQL IDE

app.use('/graphiql', graphiqlExpress({endpointURL: '/graphql'}))

运行

启动服务

node quick-start.js

npm script

运行 GraphiQL IDE 编辑器

输入网址 http://localhost:3000/graphiql

GraphiQL IDE

你可以试着改变查询条件
{
  books {
    title
    author
  }
}

与服务器通讯

抓包看看

GraphQL Request

  • URL 是代码中定义的路由 Request URL: http://localhost:3000/graphql?
  • GraphiQL IDE 默认用 POST 方式
  • 请求数据体
{
  "query": "{\n  books {\n    title\n    author\n  }\n}\n",
  "variables": null,
  "operationName": null
}
query 查询体
variables 参数
operationName 操作名称

参考