Blogs

GraphQL 初心者向けガイド:Node.js プロジェクトの簡単なセットアップ

November 23, 2023

GraphQLは、その柔軟性とデータ処理の効率性により、近年非常に人気が高まっています。このガイドでは、GraphQL の基本、GraphQL が提供する利点、GraphQL を使用して Node.js プロジェクトをセットアップする手順について順を追って説明します。

GraphQL とは何ですか?

GraphQL は、フェイスブックが開発した API 用のクエリ言語です。さまざまなリソースの固定エンドポイントを公開する従来の REST API とは異なり、GraphQL ではクライアントは必要なデータのみをリクエストできます。これにより、より効率的かつ正確なデータ取得が可能になり、情報のオーバーフェッチやアンダーフェッチが減ります。

GraphQL のメリット:

1。効率的なデータ取得:

GraphQL では、クライアントがレスポンスの構造を指定できるため、1 回のリクエストで必要なすべてのデータを取得できます。これにより、サーバーへの複数回のラウンドトリップの必要性が最小限に抑えられます。

2。フレキシブルスキーマ:

GraphQL では、クライアントがレスポンスの構造を定義します。つまり、要件が変化しても、クライアントはサーバーを変更しなくても追加のデータや別のデータをリクエストできます。

3。厳密なタイプ:

GraphQL APIは厳密に型付けされています。つまり、クエリできるデータの種類は明示的に定義されています。これにより、データの一貫性が確保され、利用可能な操作に関する明確な文書化が可能になります。

GraphQL を使用した Node.js プロジェクトのセットアップ:

それでは、GraphQL を使用して Node.js プロジェクトをセットアップする実際的な側面について詳しく見ていきましょう。GraphQL を Node.js アプリケーションに統合するための一般的なオプションとして、Express と Apollo Server の 2 つがあります。

このシリーズでは、Apollo サーバーを使用します

アポロサーバー は、あらゆる GraphQL スキーマで動作する、コミュニティ主導型のオープンソースの GraphQL サーバーです。基本設定は次のとおりです。

1。依存関係のインストール:

 npm install @apollo/server graphql
 npm install --save-dev typescript @types/node

2。tsconfig.json を作成します。

 npx tsc --init --rootDir src --outDir dist --lib dom,es6 --module commonjs --removeComments

3。Apollo サーバーの作成:

'を作成src' a の付いたディレクトリ 「サーバー。」 ファイル

 import { ApolloServer } from '@apollo/server';
 import { startStandaloneServer } from '@apollo/server/standalone';

 // A schema is a collection of type definitions (hence "typeDefs")
 // that together define the "shape" of queries that are executed against
 // your data.

 const typeDefs = `#graphql
 # 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.
 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).
 type Query {
     books: [Book]
 }
 `;

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

 // Resolvers define the technique for fetching the types defined in the
 // schema. This resolver retrieves books from the "books" array above.
 const resolvers = {
     Query: {
         books: () => books,
     },
 };

 // The ApolloServer constructor requires two parameters: your schema
 // definition and your set of resolvers.
 const server = new ApolloServer({
     typeDefs,
     resolvers,
 });

 startStandaloneServer(server, { listen: { port: 4000 } })
     .then(({url}:any)=>{
         console.log(`🚀 Server listening at: ${url}`);
     });

4。package.json スクリプトを調整してください。

 "scripts": {
   "start:dev": "npm run build:dev",
   "build:dev": "nodemon 'src/server.ts' --exec 'ts-node' src/server.ts -e ts,graphql"
 }

5。サーバーの起動:

 npm run start:dev

6。最終出力:

graphql api

おめでとう!GraphQL の世界への第一歩を踏み出しました。これで、GraphQL とその利点、Express または Apollo Server を使用して Node.js プロジェクトを設定する方法についての基本的な理解ができました。今後の記事では、GraphQL のスキーマとリゾルバーを探り、この強力なテクノロジーを使った堅牢な API の構築について詳しく説明します。

完全なサンプルは Github で閲覧およびフォークできます。 graphql サーバーのセットアップ

Node.js で GraphQL をマスターする方法について、さらにエキサイティングなコンテンツをお楽しみに!