201212 TIL ApolloClient&ApolloExpress

ToastEggsToast·2020년 12월 12일
0

TIL

목록 보기
6/15

Apollo

Apollo Client

Apollo Client is a comprehensive state management library for JavaScript that enables you to manage both local and remote data with GraphQL. Use it to fetch, cache, and modify application data, all while automatically updating your UI.

Apollo Client는 GraphQL 기반의 라이브러리로, 클라이언트 애플리케이션의 GraphQL과 데이터 교환을 돕는다. useQuery, useMutation 등의 hook들을 사용해 쿼리를 보내 데이터를 요청한다.

설치하기

npm install @apollo/client graphql 혹은 yarn add @apollo/client graphql 을 입력해 graphql과 apollo client를 설치한다.

Client 생성하기

graphql서버의 url 주소를 정의해줄 ApolloClient instance의 initialize를 해준다.

import { ApolloClient, InMemoryCache } from '@apollo/client';

const client = new ApolloClient({
  uri: 'GRAPHQL_RUNNING_SERVER_ADDRESS',
  cache: new InMemoryCache()
});

React/React-Native App 에 Apollo Client 연결하기

@apollo/client에서 ApolloProvider 컴포넌트를 import해서 최상단에 감싸준다.

import React from 'react';
import { render } from 'react-dom';

import { ApolloProvider } from '@apollo/client';

function App() {
  return (
    <ApolloProvider client={client}>
      <div>
        <h2>My first Apollo app 🚀</h2>
      </div>
    </ApolloProvider>
  );
}

render(<App />, document.getElementById('root'));

ApolloProvider를 최상단에 위치시킴으로써 컴포넌트의 어느 위치든 닿을 수 있도록 해준다.
client props에 선언했던 client를 연결시켜준다.

Apollo Client가 앱단에서 설정해주는 영역이라면, Apollo Express는 서버단에서 설정해주는 영역이다.

Apollo Express

This is the Express and Connect integration of GraphQL Server. Apollo Server is a community-maintained open-source GraphQL server that works with all Node.js HTTP server frameworks: Express, Connect, Hapi, Koa and Restify. Read the docs. Read the CHANGELOG.

GraphQl Server에서 사용이 가능한 express이다.

설치하기

npm install apollo-server-express 또는 yarn add apollo-server-express로 설치해준다.

Express

import express from 'express';
import bodyParser from 'body-parser';
import { graphqlExpress } from 'apollo-server-express';

const myGraphQLSchema = // ... define or import your schema here!
const PORT = 3000;

const app = express();

// bodyParser is needed just for POST.
app.use<('/graphql', bodyParser.json(), graphqlExpress({ schema: myGraphQLSchema }));

app.listen(PORT);

Express를 임포트해서, graphql Schema를 선언해주고 사용할 수 있도록 연결해준다.

Graphql의 특징 중 하나는 엔드포인트를 하나만 사용한다는 점이다.
따라서 일반적인 경우와 다르게 app.use하나에서 모든것을 정리할 수 있다.

profile
개발하는 반숙계란 / 하고싶은 공부를 합니다. 목적은 흥미입니다.

0개의 댓글