Project

Graphql 리액트 연결

프도의길 2023. 8. 22. 20:24

요즘 이직 준비하면서 Graphql 사용하는 회사들이 많아진 걸 느낍니다.

이번 포스트에서 Graphql 연결 방법에 대해서 알아보겠습니다.

npm i @apollo/client graphql 라이브러리 설치를 진행 해줍니다.

src/graphql/apollo-client-ts
import { ApolloClient, HttpLink, InMemoryCache } from "@apollo/client";

const httpLink = new HttpLink({
  uri: "http://localhost:4000/graphql",
  credentials: "include",
});

export const client = new ApolloClient({
  link: httpLink,
  cache: new InMemoryCache(),
});

서버로 보낼 httpLink 만들어주고 

//_app.tsx
import { SessionProvider } from "next-auth/react";
import { ChakraProvider } from "@chakra-ui/react";
import type { AppProps } from "next/app";
import { theme } from "@/chakra/theme";
import { ApolloProvider } from "@apollo/client";
import { client } from "@/graphql/apollo-client";
import { Toaster } from "react-hot-toast";

export default function App({
  Component,
  pageProps: { session, ...pageProps },
}: AppProps) {
  return (
    <ApolloProvider client={client}>
      <SessionProvider session={session}>
        <ChakraProvider theme={theme}>
          <Component {...pageProps} />
          <Toaster />
        </ChakraProvider>
      </SessionProvider>
    </ApolloProvider>
  );
}

app.tsx 파일에다 전역시켜줍니다.

 

그리고 백엔드 쪽은

npm install apollo-server-express apollo-server-core express graphql 설치 해줍니다.

참고 자료https://www.apollographql.com/docs/apollo-server/v3/integrations/middleware

 

Choosing an Apollo Server package

Use the right package for your project

www.apollographql.com

//index.ts
import { ApolloServer } from "apollo-server-express";
import {
  ApolloServerPluginDrainHttpServer,
  ApolloServerPluginLandingPageLocalDefault,
} from "apollo-server-core";
import { makeExecutableSchema } from "@graphql-tools/schema";
import express from "express";
import http from "http";
import typeDefs from "./graphql/typeDefs";
import resolvers from "./graphql/resolvers";
import { getSession } from "next-auth/react";
import { GraphQLContext, Session } from "./util/types";
import * as dotenv from "dotenv";
import { PrismaClient } from "@prisma/client";

async function main() {
  dotenv.config();
  const app = express();
  const httpServer = http.createServer(app);

  const schema = makeExecutableSchema({
    typeDefs,
    resolvers,
  });

  const corsOptions = {
    origin: process.env.CLIENT_ORIGIN,
    credentials: true,
  };

  const prisma = new PrismaClient();

  const server = new ApolloServer({
    schema,
    csrfPrevention: true,
    cache: "bounded",
    context: async ({ req, res }): Promise<GraphQLContext> => {
      const session = (await getSession({ req })) as Session;

      return { session, prisma };
    },
    plugins: [
      ApolloServerPluginDrainHttpServer({ httpServer }),
      ApolloServerPluginLandingPageLocalDefault({ embed: true }),
    ],
  });
  await server.start();
  server.applyMiddleware({ app, cors: corsOptions });
  await new Promise<void>((resolve) =>
    httpServer.listen({ port: 4000 }, resolve)
  );
  console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);
}

main().catch((err) => console.log(err));

코드중에 schema 변수에 makeExecutableSchema()메소드가 있습니다

npm i @graphql-tools/schema 설치해줍니다 그래야 makeExecutableSchema 사용할 수 있습니다.

그러면 graphql 스키마 api를 만들어 보겠습니다.

src/graphql/typeDefs/user.ts
import { gql } from "apollo-server-core";

const typeDefs = gql`
  type SearchedUser {
    id: String
    username: String
  }

  type Query {
    searchUsers(username: String): [SearchedUser]
  }

  type Mutation {
    createUsername(username: String): CreateUsernameResponse
  }

  type CreateUsernameResponse {
    success: Boolean
    error: String
  }
`;

export default typeDefs;
/////////////////////////////////////////////////////
src/graphql/typeDefs/index.ts
import userTypeDefs from "./user";

const typeDefs = [userTypeDefs];

export default typeDefs;

그리고 typeDef 해준걸 resolver 해야합니다

src/graphql/resolvers/user.ts

const resolvers = {
  Query: {
    searchUsers:()=>{},
  },
  Mutation: {
    createUsername:()=>{},
  },
};

export default resolvers;

////////////////////////////////////
src/graphql/resolvers/index.ts
import userResolvers from "./user";

import merge from "lodash.merge";

const resolvers = merge({}, userResolvers);

export default resolvers;

이렇게 선언해준걸 위쪽 index.ts 파일에 makeExecutableSchema({ typeDefs, resolvers,}) 해줍니다

따로 graphql 중요부분은 블로그 해놓겠습니다.

'Project' 카테고리의 다른 글

WebSocket/ Subscription  (0) 2023.08.29
GraphQL 대화 생성  (0) 2023.08.28
GraphQL- 유저 검색 기능  (0) 2023.08.23
Graphql Query, prisma  (0) 2023.08.22
next-auth 적용하여 소셜 로그인 구현하기  (0) 2023.08.22