0Pricing
Node.js Backend Development Bootcamp · 课时

使用 Apollo 构建 GraphQL 服务器

使用 Apollo Server 在 Node.js 中实现 GraphQL API,将其连接到数据源并定义解析器

使用 Apollo 构建 GraphQL 服务器 是 CoddyKit 上的免费 Node.js Backend Development Bootcamp 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Node.js Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Node.js Backend Development Bootcamp 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Meet Apollo Server

Welcome to building a GraphQL server! We'll use Apollo Server, a popular open-source library that helps you implement a production-ready GraphQL API in Node.js.

  • It's easy to set up.
  • It integrates with many Node.js frameworks like Express.
  • It provides powerful tools like GraphQL Playground for testing.

Apollo Server handles the heavy lifting, letting you focus on your data.

使用 Apollo 构建 GraphQL 服务器 — 插图 1

Project Setup for Apollo

Let's get started by setting up our project. Open your terminal and run these commands to create a new Node.js project and install the required libraries:

  • apollo-server: The core library for building our GraphQL server.
  • graphql: The JavaScript implementation of the GraphQL specification.

Here's how to do it:

mkdir my-graphql-api
cd my-graphql-api
npm init -y
npm install apollo-server graphql

Once installed, you're ready to write some code!

Schema & Resolvers: The Core

A GraphQL server has two main parts:

  • Schema (Type Definitions): This defines the shape of your data and the operations clients can perform (queries, mutations). Think of it as the contract between client and server.
  • Resolvers: These are functions that tell GraphQL how to fetch the data for each type and field defined in your schema. They are the "backend logic" for your API.

Together, they define your API's capabilities and how it interacts with your data.

Crafting Your GraphQL Schema

We define the schema using a special template literal tag called gql (from apollo-server). This allows us to write GraphQL Schema Definition Language (SDL).

The most important type is Query, which defines all the ways clients can read data from your API. Let's define a simple Query that returns a "hello" message.

const { gql } = require('apollo-server');

const typeDefs = gql`
  type Query {
    hello: String
  }
`;

console.log('Your schema is ready!');

Building Your Resolvers

Now that we have our schema, we need to tell GraphQL how to actually get the data for the hello field. This is where resolvers come in.

Resolvers are functions that match the fields in your schema. When a client queries hello, the corresponding resolver function will be executed.

const resolvers = {
  Query: {
    hello: () => 'Hello from your GraphQL API!',
  },
};

console.log('Resolvers are defined!');

Launching Your First Server

Let's put it all together! We'll combine the typeDefs and resolvers with ApolloServer to create a complete, runnable GraphQL server.

Create a file named index.js and add the following code. Then, run it with node index.js.

const { ApolloServer, gql } = require('apollo-server');

// 1. Define your schema (type definitions)
const typeDefs = gql`
  type Query {
    hello: String
  }
`;

// 2. Define your resolvers (how to fetch data)
const resolvers = {
  Query: {
    hello: () => 'Hello from your GraphQL API!',
  },
};

// 3. Create an Apollo Server instance
const server = new ApolloServer({ typeDefs, resolvers });

// 4. Start the server
server.listen({ port: 4000 }).then(({ url }) => {
  console.log(`🚀 Server ready at ${url}`);
  console.log('Try opening your browser to test it!');
});

Defining Custom Data Types

A simple "hello" isn't very exciting. Let's define a custom type, like Book, with its own fields. This shows how you structure more complex data.

Update your typeDefs to include the Book type and a books query that returns a list of them.

const { gql } = require('apollo-server');

const typeDefs = gql`
  type Book {
    title: String
    author: String
  }

  type Query {
    hello: String
    books: [Book]
  }
`;

console.log('Schema updated with Book type!');

Resolving Custom Types

To make the books query work, we need to update our resolvers. For now, we'll use an in-memory array of objects to simulate a database. In real applications, resolvers connect to databases or other APIs.

Let's update the resolvers to provide data for our books query.

const books = [
  {
    title: 'The Great Gatsby',
    author: 'F. Scott Fitzgerald',
  },
  {
    title: 'To Kill a Mockingbird',
    author: 'Harper Lee',
  },
];

const resolvers = {
  Query: {
    hello: () => 'Hello from your GraphQL API!',
    books: () => books,
  },
};

console.log('Resolvers updated for books!');

Full API with Books

Here's the complete index.js file with our new Book type and its resolver. Run this with node index.js.

Once running, open the URL in your browser (e.g., http://localhost:4000). You'll see the GraphQL Playground, where you can test queries like:

query {
  books {
    title
    author
  }
}

const { ApolloServer, gql } = require('apollo-server');

const typeDefs = gql`
  type Book {
    title: String
    author: String
  }

  type Query {
    hello: String
    books: [Book]
  }
`;

const books = [
  {
    title: 'The Great Gatsby',
    author: 'F. Scott Fitzgerald',
  },
  {
    title: 'To Kill a Mockingbird',
    author: 'Harper Lee',
  },
];

const resolvers = {
  Query: {
    hello: () => 'Hello from your GraphQL API!',
    books: () => books,
  },
};

const server = new ApolloServer({ typeDefs, resolvers });

server.listen({ port: 4000 }).then(({ url }) => {
  console.log(`🚀 Server ready at ${url}`);
  console.log('Explore your API in GraphQL Playground!');
});

Schema vs. Resolvers Check

You've learned about the two fundamental parts of a GraphQL server: the schema (type definitions) and the resolvers.

Which of the following best describes the primary role of GraphQL Resolvers in an Apollo Server?

Apollo Server: Quick Recap

Great job! You've successfully built your first GraphQL server with Apollo Server.

  • We installed apollo-server and graphql.
  • We defined our API's structure using Type Definitions (typeDefs) written in GraphQL SDL.
  • We implemented Resolvers to specify how to fetch data for the fields in our schema, using mock data.
  • We launched our server using ApolloServer and explored it with GraphQL Playground.

This is the foundation for building powerful and flexible GraphQL APIs. Next, you can explore mutations, arguments, and connecting to real databases!

常见问题解答

「使用 Apollo 构建 GraphQL 服务器」课时是免费的吗?

是的 — 「使用 Apollo 构建 GraphQL 服务器」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Node.js Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 Node.js Backend Development Bootcamp 课程共包含 4 节课。

「使用 Apollo 构建 GraphQL 服务器」这节课中我会学到什么?

使用 Apollo Server 在 Node.js 中实现 GraphQL API,将其连接到数据源并定义解析器 你通过在浏览器中直接运行的动手代码来练习 Node.js Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Node.js Backend Development Bootcamp 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Node.js Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「使用 Apollo 构建 GraphQL 服务器」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Node.js Backend Development Bootcamp 课中编写并运行代码吗?

能。每节 Node.js Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Node.js 无服务器简介
  2. GraphQL API 设计原则
  3. 使用 Apollo 构建 GraphQL 服务器
  4. 用于实时数据的 GraphQL 订阅
← 返回 Node.js Backend Development Bootcamp