0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ApolloでGraphQLサーバを構築する

0
Posted at

1. はじめに

  • ローカル環境にGraphQLサーバを構築したい
  • IDEはVSCodeを使用したい

2. 開発環境

  • Apollo Server 5.4.0
  • GraphQl 16.13.0
  • Node.js 24.12.0
  • Visual Studio Code
  • JavaScript
  • Windows 11

3. GrapQLサーバ用のプロジェクトの作成

3.1. プロジェクトの作成

  • 任意のフォルダで新しいプロジェクト用のディレクトリを作成する
mkdir graphql-server-example
cd graphql-server-example

3.2. Visual Studio Codeの起動

code .

image.png

3.3. Node.jsプロジェクトの初期化

npm init --yes && npm pkg set type="module"

3.4. Apollo ServerとGraphQLのインストール

npm install @apollo/server graphql graphql-tag

4. package.jsonの編集

  • JavaScriptファイルをESモジュールとして読み込むため、package.jsonのtypeフィールドをmoduleに設定する
- "scripts": {
-   "test": "echo \"Error: no test specified\" && exit 1"
- },
+ "scripts": {
+   "start": "node index.js"
+ },

image.png

5. index.jsの作成

  • srcフォルダ内にindex.jsを作成し、スキーマ、データ、リゾルバを定義する
src/index.js
import { ApolloServer } from "@apollo/server";
import { startStandaloneServer } from "@apollo/server/standalone";
import { gql } from "graphql-tag";

// GraphQL schema definition
const typeDefs = gql`
  type Query {
    hello: String
    }
`;

// Resolvers define
const resolvers = {
  Query: {
    hello: () => "Hello, world!",
  },
};

// Create an instance of ApolloServer
const server = new ApolloServer({ typeDefs, resolvers });
// Start the server

startStandaloneServer(server).then(({ url }) => {
  console.log(`Server ready at ${url}`);
});

image.png

6. サーバの起動

node .\src\index.js 

image.png

7. クエリの実行

  • ブラウザで http://localhost:4000 にアクセスし、GraphQL Playgroundを開く
  • ExampleQueryボタンをクリックして、レスポンスが帰ってくることを確認する
    image.png

8. 参考文献

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?