Get Started with Apollo Server
This tutorial helps you:
-
Obtain a basic understanding of GraphQL principles
-
Define a GraphQL schema that represents the structure of your data set
-
Run an instance of Apollo Server that lets you execute queries against your schema
This tutorial assumes that you are familiar with the command line and JavaScript and have installed a recent Node.js (v14.16.0+) version. Additionally, for those interested, this tutorial includes an optional section describing how to set up Apollo Server with TypeScript.
Step 1: Create a new project
-
From your preferred development directory, create a directory for a new project and
cd
into it:
1mkdir graphql-server-example
2cd graphql-server-example
-
Initialize a new Node.js project with
npm
(or another package manager you prefer, such as Yarn):
1 npm init --yes && npm pkg set type="module"
This getting started guide sets up a project using ES Modules, which simplifies our examples and allows us to use top-level
await
.
Your project directory now contains a package.json
file.
Step 2: Install dependencies
Applications that run Apollo Server require two top-level dependencies:
-
graphql
(also known asgraphql-js
) is the library that implements the core GraphQL parsing and execution algorithms. -
@apollo/server
is the main library for Apollo Server itself. Apollo Server knows how to turn HTTP requests and responses into GraphQL operations and run them in an extensible context with support for plugins and other features.
Run the following command to install both of these packages and save them in your project's node_modules
directory:
1 npm install @apollo/server graphql
Follow the instructions below to set up with either TypeScript or JavaScript:
Set up with TypeScript (**Recommended**) Set up with JavaScriptStep 3: Define your GraphQL schema
ⓘ note The code blocks below use TypeScript. If your project uses JavaScript, you need to transpile the code.Every GraphQL server (including Apollo Server) uses a schema to define the structure of data that clients can query. In this example, we'll create a server for querying a collection of books by title and author.
Open index.ts
in your preferred code editor and paste the following into it:
1import { ApolloServer } from '@apollo/server';
2import { startStandaloneServer } from '@apollo/server/standalone';
3
4// A schema is a collection of type definitions (hence "typeDefs")
5// that together define the "shape" of queries that are executed against
6// your data.
7const typeDefs = `#graphql
8 # Comments in GraphQL strings (such as this one) start with the hash (#) symbol.
9
10 # This "Book" type defines the queryable fields for every book in our data source.
11 type Book {
12 title: String
13 author: String
14 }
15
16 # The "Query" type is special: it lists all of the available queries that
17 # clients can execute, along with the return type for each. In this
18 # case, the "books" query returns an array of zero or more Books (defined above).
19 type Query {
20 books: [Book]
21 }
22`;
Adding
#graphql
to the beginning of a template literal provides GraphQL syntax highlighting in supporting IDEs.
This snippet defines a simple, valid GraphQL schema. Clients will be able to execute a query named books
, and our server will return an array of zero or more Book
s.
Step 4: Define your data set
Now that we've defined the structure of our data, we can define the data itself.
Apollo Server can fetch data from any source you connect to (including a database, a REST API, a static object storage service, or even another GraphQL server). For the purposes of this tutorial, we'll hardcode our example data.
Add the following to the bottom of your index.ts
file:
1const books = [
2 {
3 title: 'The Awakening',
4 author: 'Kate Chopin',
5 },
6 {
7 title: 'City of Glass',
8 author: 'Paul Auster',
9 },
10];
This snippet defines a simple data set that clients can query. Notice that the two objects in the array each match the structure of the Book
type we defined in our schema.
Step 5: Define a resolver
We've defined our data set, but Apollo Server doesn't know that it should use that data set when it's executing a query. To fix this, we create a resolver.
Resolvers tell Apollo Server how to fetch the data associated with a particular type. Because our Book
array is hardcoded, the corresponding resolver is straightforward.
Add the following to the bottom of your index.ts
file:
1// Resolvers define how to fetch the types defined in your schema.
2// This resolver retrieves books from the "books" array above.
3const resolvers = {
4 Query: {
5 books: () => books,
6 },
7};
Step 6: Create an instance of ApolloServer
We've defined our schema, data set, and resolver. Now we need to provide this information to Apollo Server when we initialize it.
Add the following to the bottom of your index.ts
file:
1// The ApolloServer constructor requires two parameters: your schema
2// definition and your set of resolvers.
3const server = new ApolloServer({
4 typeDefs,
5 resolvers,
6});
7
8// Passing an ApolloServer instance to the `startStandaloneServer` function:
9// 1. creates an Express app
10// 2. installs your ApolloServer instance as middleware
11// 3. prepares your app to handle incoming requests
12const { url } = await startStandaloneServer(server, {
13 listen: { port: 4000 },
14});
15
16console.log(`
标签:Started,Server,server,GraphQL,our,Apollo,your
From: https://www.cnblogs.com/sexintercourse/p/18566285