# \[GRAPHQL] Get started with Apollo Server (ok)

### [Step 1: Create a new project](https://www.apollographql.com/docs/apollo-server/getting-started/#step-1-create-a-new-project) <a href="#step-1-create-a-new-project" id="step-1-create-a-new-project"></a>

&#x20;From your preferred development directory, create a directory for a new project and `cd` into it:

```
mkdir graphql-server-example
cd graphql-server-example
```

&#x20;Initialize a new Node.js project with `npm` (or another package manager you prefer, such as Yarn):

```
npm init --yes
```

&#x20;Your project directory now contains a `package.json` file.

### [Step 2: Install dependencies](https://www.apollographql.com/docs/apollo-server/getting-started/#step-2-install-dependencies) <a href="#step-2-install-dependencies" id="step-2-install-dependencies"></a>

Applications that run Apollo Server require two top-level dependencies:

* [`apollo-server`](https://npm.im/apollo-server) is the core library for Apollo Server itself, which helps you define the shape of your data and how to fetch it.
* [`graphql`](https://npm.im/graphql) is the library used to build a GraphQL schema and execute queries against it.

Run the following command to install both of these dependencies and save them in your project's `node_modules` directory:

```
npm install apollo-server graphql
```

&#x20;Also create an empty `index.js` file in your project's root directory:

```
touch index.js
```

&#x20;To keep things simple, `index.js` will contain **all** of the code for this example application.

### [Step 3: Define your GraphQL schema](https://www.apollographql.com/docs/apollo-server/getting-started/#step-3-define-your-graphql-schema) <a href="#step-3-define-your-graphql-schema" id="step-3-define-your-graphql-schema"></a>

&#x20;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.

Mọi máy chủ GraphQL (bao gồm cả Máy chủ Apollo) đều sử dụng lược đồ để xác định cấu trúc dữ liệu mà máy khách có thể truy vấn. Trong ví dụ này, chúng tôi sẽ tạo một máy chủ để truy vấn bộ sưu tập sách theo tên sách và tác giả.

&#x20;Open `index.js` in your preferred editor and paste the following into it:

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

// A schema is a collection of type definitions (hence "typeDefs")
// that together define the "shape" of queries that are executed against your data.
// Một lược đồ là một tập hợp các định nghĩa kiểu (do đó "typeDefs") 
// cùng nhau xác định "hình dạng" của các truy vấn được thực thi dữ liệu của bạn.
const typeDefs = gql`
  # Comments in GraphQL strings (such as this one) start with the hash (#) symbol.
  # This "Book" type defines the queryable fields for every book in our data source.
  # Nhận xét trong chuỗi GraphQL (chẳng hạn như chuỗi này) bắt đầu bằng ký hiệu băm (#).
  # Loại "Sách" này xác định các trường có thể truy vấn cho mọi sách trong nguồn dữ liệu của chúng tôi.
  type Book {
    title: String
    author: String
  }

  # The "Query" type is special: it lists all of the available queries that
  # clients can execute, along with the return type for each. In this
  # case, the "books" query returns an array of zero or more Books (defined above).
  # Loại "Truy vấn" đặc biệt: nó liệt kê tất cả các truy vấn có sẵn 
  # máy khách có thể thực thi, cùng với kiểu trả về cho mỗi máy khách. Trong này 
  # case, truy vấn "books" trả về một mảng không có hoặc nhiều Sách (đã định nghĩa ở trên).
  type Query {
    books: [Book]
  }
`;
```

Đoạn mã này xác định một giản đồ GraphQL hợp lệ, đơn giản. Khách hàng sẽ có thể thực hiện truy vấn có tên sách và máy chủ của chúng tôi sẽ trả về một mảng không có hoặc nhiều Sách.

### [Step 4: Define your data set](https://www.apollographql.com/docs/apollo-server/getting-started/#step-4-define-your-data-set) <a href="#step-4-define-your-data-set" id="step-4-define-your-data-set"></a>

Bây giờ chúng tôi đã xác định cấu trúc dữ liệu của mình, chúng tôi có thể xác định chính dữ liệu đó. Apollo Server có thể tìm nạp dữ liệu từ bất kỳ nguồn nào mà bạn kết nối (bao gồm cơ sở dữ liệu, API REST, dịch vụ lưu trữ đối tượng tĩnh hoặc thậm chí là một máy chủ GraphQL khác). Với mục đích của hướng dẫn này, chúng tôi sẽ chỉ mã hóa một số dữ liệu ví dụ.

&#x20;Add the following to the bottom of `index.js`:

```
const books = [
  {
    title: 'The Awakening',
    author: 'Kate Chopin',
  },
  {
    title: 'City of Glass',
    author: 'Paul Auster',
  },
];
```

Đoạn mã này xác định một tập dữ liệu đơn giản mà khách hàng có thể truy vấn. Lưu ý rằng hai đối tượng trong mảng phù hợp với cấu trúc của Loại sách mà chúng ta đã xác định trong lược đồ của mình.

### [Step 5: Define a resolver](https://www.apollographql.com/docs/apollo-server/getting-started/#step-5-define-a-resolver) <a href="#step-5-define-a-resolver" id="step-5-define-a-resolver"></a>

Chúng tôi đã xác định tập dữ liệu của mình, nhưng Apollo Server không biết rằng nó nên sử dụng tập dữ liệu đó khi thực hiện truy vấn. Để khắc phục điều này, chúng tôi tạo một trình phân giải.

Bộ phân giải cho Apollo Server biết cách tìm nạp dữ liệu được liên kết với một loại cụ thể. Vì mảng Sách của chúng tôi được mã hóa cứng, trình phân giải tương ứng là đơn giản.

&#x20;Add the following to the bottom of `index.js`:

```
// Resolvers define the technique for fetching the types defined in the schema.
// This resolver retrieves books from the "books" array above.
};
// Trình phân giải xác định kỹ thuật tìm nạp các kiểu được xác định trong // lược đồ. 
// Trình phân giải này truy xuất sách từ mảng "sách" ở trên.
const resolvers = {
  Query: {
    books: () => books,
  },
};
```

### [Step 6: Create an instance of `ApolloServer`](https://www.apollographql.com/docs/apollo-server/getting-started/#step-6-create-an-instance-of-apolloserver) <a href="#step-6-create-an-instance-of-apolloserver" id="step-6-create-an-instance-of-apolloserver"></a>

Chúng tôi đã xác định lược đồ, tập dữ liệu và trình phân giải của mình. Bây giờ chúng ta chỉ cần cung cấp thông tin này cho Apollo Server khi chúng ta khởi tạo nó.

&#x20;Add the following to the bottom of `index.js`:

```
// The ApolloServer constructor requires two parameters: your schema definition 
// and your set of resolvers.
// Phương thức khởi tạo ApolloServer yêu cầu hai tham số: lược đồ của bạn định nghĩa 
// và tập hợp các trình phân giải của bạn.
const server = new ApolloServer({ typeDefs, resolvers });
// The `listen` method launches a web server.
server.listen().then(({ url }) => {
  console.log(`🚀  Server ready at ${url}`);
});
```

### [Step 7: Start the server](https://www.apollographql.com/docs/apollo-server/getting-started/#step-7-start-the-server) <a href="#step-7-start-the-server" id="step-7-start-the-server"></a>

We're ready to start our server! Run the following from your project's root directory:

```
node index.js
```

You should see the following output:

```
🚀 Server ready at http://localhost:4000/
```

We're up and running!

### [Step 8: Execute your first query](https://www.apollographql.com/docs/apollo-server/getting-started/#step-8-execute-your-first-query) <a href="#step-8-execute-your-first-query" id="step-8-execute-your-first-query"></a>

![](/files/-MU9USpTBd67GTHd54Sp)

&#x20;Here's a GraphQL **query string** for executing the `books` query:

```
{
  books {
    title
    author
  }
}
```

Một trong những khái niệm quan trọng nhất của GraphQL là khách hàng có thể chọn chỉ truy vấn các trường họ cần. Xóa tác giả khỏi chuỗi truy vấn và thực thi lại. Phản hồi cập nhật để chỉ bao gồm trường tiêu đề cho mỗi cuốn sách!


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://javascriptuse.gitbook.io/advanced/graphql-get-started-with-apollo-server-ok.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
