[GRAPHQL] Get started with Apollo Server (ok)

https://www.apollographql.com/docs/apollo-server/getting-started/

From your preferred development directory, create a directory for a new project and cd into it:

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

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

npm init --yes

Your project directory now contains a package.json file.

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

  • 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 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

Also create an empty index.js file in your project's root directory:

touch index.js

To keep things simple, index.js will contain all of the code for this example application.

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ả.

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.

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ụ.

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.

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.

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,
  },
};

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ó.

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}`);
});

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!

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!

Last updated

Navigation

Lionel

@Copyright 2023