快速开始
大约十分钟
在这个guide里,我们将一起用JavaScript创建一个GraphQL server。在这个guide的最后你将:
有一个基本的GraphQL服务器,它将作为一个复杂服务器的基础。
对GraphQL的基本原理有所了解。
能够在GraphQL服务器,并且查看 Playground的响应。
Node.js 版本6以上.
如果你想跳过这些步骤,看这里,克隆下来,然后在本地运行!
第一步:init 项目
我们将在你的terminal里创建一个名为 graphql-server-example
的项目:
mkdir graphql-server-example
cd graphql-server-example
用npm来初始化你的项目
npm init --yes
我们用npm来初始化项目,当然你也可以用yarn来初始化这个项目,这里不做示例。
如果创建成果,你将看到package.json这个文件。
第二步:安装依赖
这里我们将用npm来安装两个核心依赖:
apollo-server
: 这个定义apollo服务。graphql
: 这个用来定义schema,查询数据。
注意:本指南中不会使用graphql包,但需要单独安装,因为它是Apollo Server的重要的“对等依赖”。
这两个核心依赖让你更加简单的来创建GraphQL服务,然后你可以写任何你想要的代码。
运行下面这条命令来安装这些依赖:
npm install --save apollo-server graphql
在下一步,我们将用这些库来创建可处理响应的GraphQL服务。
第三步:创建服务
在这一步,我们提供了代码块来设置 apollo-server
来响应GraphQL的请求,在这里我们允许你复制粘贴下面的代码块到index.js中。我们希望在你阅读代码的时候 里面的注释能帮助你理解。不要担心更深的含义,后面的章节将会回答你的疑问。
示例代码利用静态的数据块来展示,这些在实际项目中都会被替代会数据库。
用编辑器打开我们第一步创建的
graphql-server-example
目录。创建一个新的
index.js
文件。把下面的代码粘贴辅助到
index.js
文件里。
const { ApolloServer, gql } = require('apollo-server');
// This is a (sample) collection of books we'll be able to query
// the GraphQL server for. A more complete example might fetch
// from an existing data source like a REST API or database.
const books = [
{
title: 'Harry Potter and the Chamber of Secrets',
author: 'J.K. Rowling',
},
{
title: 'Jurassic Park',
author: 'Michael Crichton',
},
];
// Type definitions define the "shape" of your data and specify
// which ways the data can be fetched from the GraphQL server.
const typeDefs = gql`
# Comments in GraphQL are defined with the hash (#) symbol.
# This "Book" type can be used in other type declarations.
type Book {
title: String
author: String
}
# The "Query" type is the root of all GraphQL queries.
# (A "Mutation" type will be covered later on.)
type Query {
books: [Book]
}
`;
// Resolvers define the technique for fetching the types in the
// schema. We'll retrieve books from the "books" array above.
const resolvers = {
Query: {
books: () => books,
},
};
// In the most basic sense, the ApolloServer can be started
// by passing type definitions (typeDefs) and the resolvers
// responsible for fetching the data for those types.
const server = new ApolloServer({ typeDefs, resolvers });
// This `listen` method launches a web-server. Existing apps
// can utilize middleware options, which we'll discuss later.
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
这些代码都是一个基础GraphQL所必须的一切,在下一步我们将启动服务,他已经准备好相应一些请求了!
第四步:启动服务
这一步,我们回到termeial来启动服务。
node index.js
你将会看到:
🚀 Server ready at http://localhost:4000/
在浏览器里打开这个地址。
如果一切顺利,你讲看到grapql的后台。如图:

在下步,我们将用这个来做查询。
第五步:运行你的第一个查询
这里,你要发送几个GraphQL的请求,它分为几个部分:
请求 (左边部分)
响应(右边部分)
文档(点击右边绿色的“SCHEMA” 按钮)
第一个查询是所有的books(我们代码里定义的)。
{
books {
title
author
}
}
如果你按了‘’play“ 按钮, 你将看到服务器的响应。

快速开始到这里了,后面章节将展开深入的开发。
Last updated