반응형

 

📝Apollo Server로 시작하기

Apollo Server 공식 문서와 제가 개인적으로 연습에 필요한 패키지로 진행했습니다

귀찮아서 ts가 아니라 js로 진행했다는 점 참고바랍니다

 

 

1. 프로젝트 폴더 만들기

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

 

2. Node 패키지 설치 및 셋팅

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

 

3. 필요 패키지 설치

npm install apollo-server graphql
npm install nodemon -D

 

4. 실행 파일 생성 (src/index.js)

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 books = [
    {
        title: 'The Awakening',
        author: 'Kate Chopin',
    },
    {
        title: 'City of Glass',
        author: 'Paul Auster',
    },
];

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

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

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

// Passing an ApolloServer instance to the `startStandaloneServer` function:
//  1. creates an Express app
//  2. installs your ApolloServer instance as middleware
//  3. prepares your app to handle incoming requests
const { url } = await startStandaloneServer(server, {
    listen: { port: 4000 },
});

console.log(`🚀  Server ready at: ${url}`);

 

5. 실행 스크립트 작성 (package.json)

{
  "dependencies": {
    "@apollo/server": "^4.10.2",
    "apollo-server": "^3.13.0",
    "graphql": "^16.8.1"
  },
  "devDependencies": {
    "nodemon": "^3.1.0"
  },
  "name": "graphql-server-example",
  "version": "1.0.0",
  "main": "src/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon src/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "type": "module"
}

 

6. npm start로 시작

localhost:4000/grpahql로 apollo server 접속

 

 

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

 

Get started with Apollo Server

This tutorial helps you: Obtain a basic understanding of GraphQL principlesDefine a GraphQL schema that represents the structure of your data setRun an instance of Apollo Server that lets you execute queries against your schema This tutorial assumes that y

www.apollographql.com

 

반응형