Nodejs

GraphQl과 Apollo

마손리 2022. 12. 23. 16:41

GraphQL이란? 

GraphQL이란 페이스북에서 제작한 API를 위한 쿼리 언어이다. GraphQL만의 특징으로는 사용자에게 전체 데이터가아닌 필요한 데이터만을 골라 제공할수있다. 또한 REST API와 다르게 단일 엔드포인트를 사용한다. 

예를 들어 REST API의 경우 "example.com/home", "example.com/user"와 같이 URL의 엔드포인트를 이용하여 통신이 되지만 GraphQL의 경우 "example.com/graphql" 하나로 원하는 데이터를 가저올수 있다.

 

npm install @apollo/server graphql

먼저 npm을 이용해 apollo와 graphql을 설치

 

server.js (index.js)

import { ApolloServer, gql } from "apollo-server";

const typeDefs = gql`	//GraphQL 쿼리문
  type Query {
    hello: String
  }
`;
const resolvers = {		//요청이 들어왔을때 실행할 코드들
  Query: {
    hello: () => "baby",
  },
};

const server = new ApolloServer({		//서버가동
  typeDefs,
  resolvers,
});
server.listen().then(({ url }) => {
  console.log(`🚀  Server ready at ${url}`);
});

서버를 가동시킬 파일을 하나 만든뒤 위와 같이 작성해주면 끝이난다.

 

typeDefs

그래프큐엘의 쿼리문이 작성되는곳으로 타입으로는 Query와 Mutation으로 나뉜다. 각각 Query는 REST에서의 get을 담당하고 Mutation은 나머지 post, put, delete들과 같은 일을 담당한다. 

이후 쿼리의 이름(여기서는 "hello")과 리턴타입을 정의해준다.

 

resolvers

쿼리문을 통해서 요청이 들어왔을때 실행될 코드들이다. typeDefs에서 hello라는 요청의 리턴값이 String이므로 "baby"라는 문자값을 리턴해주었다.

 

이후 설치한 ApolloServer를 이용하여 작성된 typeDefs와 resolvers를 넣어주고 실행해주면 서버가 가동이된다.

(아폴로서버의 버전차이로 서버가동이 안될수도 있다. 위와 같이 진행이 안될경우 공식문서를 참조, https://www.apollographql.com/docs/apollo-server/getting-started)

 

Schema 통합 관리

위의 코드대로 진행할경우 몇가지의 쿼리문만 더 추가해줘도 server.js파일이 너무 복잡해진다. 그래서 typeDefs와 resolvers의 파일들을 분리해내고 이것들을 추적하고 통합하여 관리할 필요가 있다.

npm i @graphql-tools/load-files @graphql-tools/merge @graphql-tools/schema

그래프큐엘 툴들을 설치 후

위의 typeDefs와 resolvers를 각각 다른 파일에 분리시켜준다.

 

ex)

example.typeDefs.js 파일을 생성 후 내용 복사

const typeDefs = gql`	
  type Query {
    hello: String
  }
`;

example.resolvers.js 파일을 생성 후 내용 복사

const resolvers = {
  Query: {
    hello: () => "baby",
  },
};

 

schema.js

schema.js파일을 생성한뒤 (server.js와 같은위치)

import { loadFilesSync } from "@graphql-tools/load-files";
import { mergeResolvers, mergeTypeDefs } from "@graphql-tools/merge";
import { makeExecutableSchema } from "@graphql-tools/schema";


const typeDefsArray = loadFilesSync(`${__dirname}/**/*.typeDefs.js`);
const resolversArray = loadFilesSync(`${__dirname}/**/*.resolvers.js`);
// typeDefs과 reolvers의 파일 정의(각 파일들의 추적에 사용)

const mergedTypeDefs = mergeTypeDefs(typeDefsArray);
const mergedResolvers = mergeResolvers(resolversArray);
// 추적된 파일들을 통합

const schema = makeExecutableSchema({
  typeDefs: mergedTypeDefs,
  resolvers: mergedResolvers,
});
// 추적된 파일들을 사용가능하도록 분류

export default schema;

 

`${__dirname}/**/*.typeDefs.js`의 의미는 root  directory의 모든 폴더 안의 모든 typeDefs.js를 사용한다는 것이며 resolvers 또한 동일하다.

 

위와 같이 작성이 끝나면 모든 스키마들은 통합관리되며 server.js파일을 수정해주면 끝이난다.

 

server.js 수정

import { ApolloServer, gql } from "apollo-server";
import schema from "./schema"; 

const server = new ApolloServer({		
	schema,
});
server.listen().then(({ url }) => {
  console.log(`🚀  Server ready at ${url}`);
});

위와 같이 작성되었던 typeDefs와 resolvers를 지워주고 schema를 불러오기만 하면 끝이난다.

 

 

(Github:https://github.com/Mason3144/insta-clone-backend/commit/fc995c7971d89a1821817f664e8f4c300f35a410#diff-9d9b7431c19b6e202dee7ee7e908427ffc80d4af97ebe02427d3b6430c635481, graphql-tools의 버전이 다르므로 참고만 하시길 바랍니다.)

 

'Nodejs' 카테고리의 다른 글

GraphQL API  (0) 2022.12.29
REST API  (0) 2022.12.26
GraphQL에서 파일 업로드  (0) 2022.12.24
AWS-s3, multer, multer-s3를 이용한 express 파일업로드  (0) 2022.12.23
Express 서버에 Mysql과 session store 설치(AWS-RDS이용)  (0) 2022.12.14