REST API를 통해 GraphQL을 사용하여 React 애플리케이션 향상

Mary-Kate Olsen
풀어 주다: 2024-10-03 14:26:31
원래의
549명이 탐색했습니다.

급변하는 웹 개발 세계에서 애플리케이션 최적화 및 확장은 항상 문제입니다. React.js는 사용자 인터페이스를 생성하는 강력한 방법을 제공하는 도구로서 프런트엔드 개발에서 놀라운 성공을 거두었습니다. 그러나 특히 여러 REST API 엔드포인트의 경우 애플리케이션이 성장하면 복잡해집니다. 필요한 것보다 과도한 데이터를 가져오는 등의 우려는 성능 병목 현상과 열악한 사용자 경험의 원인이 될 수 있습니다.

이러한 문제에 대한 솔루션 중에는 React 애플리케이션과 함께 GraphQL을 사용하는 것이 있습니다. 백엔드에 여러 REST 엔드포인트가 있는 경우 내부적으로 REST API 엔드포인트를 호출하는 GraphQL 레이어를 도입하면 애플리케이션의 오버페치를 방지하고 프런트엔드 애플리케이션을 간소화할 수 있습니다. 이 기사에서는 이를 사용하는 방법, 이 접근 방식의 장점과 단점, 다양한 과제에 대해 설명합니다. 그리고 이를 해결하는 방법. 또한 GraphQL이 데이터 작업 방식을 개선하는 데 어떻게 도움이 되는지에 대한 몇 가지 실제 사례에 대해서도 자세히 알아볼 것입니다.

REST API의 오버페치

REST API에서 오버페치는 API가 클라이언트에 전달하는 데이터의 양이 클라이언트가 요구하는 것보다 많은 경우 발생합니다. 이는 종종 고정된 개체 또는 응답 스키마를 반환하는 REST API의 일반적인 문제입니다. 이 문제를 더 잘 이해하기 위해 예를 고려해 보겠습니다.

사용자의 이름과 이메일만 표시하면 되는 사용자 프로필 페이지를 생각해 보세요. 일반적인 REST API를 사용하면 사용자 데이터를 가져오는 방법은 다음과 같습니다.

fetch('/api/users/1')
  .then(response => response.json())
  .then(user => {
    // Use the user's name and profilePicture in the UI
  });
로그인 후 복사

API 응답에 불필요한 데이터가 포함됩니다.

{
  "id": 1,
  "name": "John Doe",
  "profilePicture": "/images/john.jpg",
  "email": "john@example.com",
  "address": "123 Denver St",
  "phone": "111-555-1234",
  "preferences": {
    "newsletter": true,
    "notifications": true
  },
  // ...more details
}
로그인 후 복사

애플리케이션에는 사용자의 이름과 이메일 필드만 필요하지만 API는 전체 사용자 개체를 반환합니다. 이러한 추가 데이터는 종종 페이로드 크기를 늘리고, 더 많은 대역폭을 차지하며, 리소스가 제한되어 있거나 네트워크 연결이 느린 장치에서 사용될 때 결국 애플리케이션 속도를 저하시킬 수 있습니다.

솔루션으로서의 GraphQL

GraphQL은 클라이언트가 필요한 데이터를 정확하게 요청할 수 있도록 하여 오버페치 문제를 해결합니다. GraphQL 서버를 애플리케이션에 통합하면 기존 REST API와 통신하는 유연하고 효율적인 데이터 가져오기 계층을 생성할 수 있습니다.

작동 방식

  1. GraphQL 서버 설정: React 프런트엔드와 REST API 사이의 중개자 역할을 하는 GraphQL 서버를 소개합니다.
  2. 스키마 정의: 프런트엔드에 필요한 데이터 유형과 쿼리를 지정하는 GraphQL 스키마를 정의합니다.
  3. 리졸버 구현: REST API에서 데이터를 가져오고 필요한 필드만 반환하는 GraphQL 서버에 리졸버를 구현합니다.
  4. 프런트엔드 통합: 직접 REST API 호출 대신 GraphQL 쿼리를 사용하도록 React 애플리케이션을 업데이트합니다.

이 접근 방식을 사용하면 기존 백엔드 인프라를 점검하지 않고도 데이터 가져오기를 최적화할 수 있습니다.

React 애플리케이션에서 GraphQL 구현

GraphQL 서버를 설정하고 이를 React 애플리케이션에 통합하는 방법을 살펴보겠습니다.

설치 종속성:

npm install apollo-server graphql axios
로그인 후 복사

스키마 정의

schema.js라는 파일을 만듭니다.

const { gql } = require('apollo-server');

const typeDefs = gql`
  type User {
    id: ID!
    name: String
    email: String  // Ensure this matches exactly with the frontend query
  }

  type Query {
    user(id: ID!): User
  }
`;

module.exports = typeDefs;
로그인 후 복사

이 스키마는 사용자 유형과 ID별로 사용자를 가져오는 사용자 쿼리를 정의합니다.

리졸버 구현

resolvers.js라는 파일을 만듭니다.

const resolvers = {
  Query: {
    user: async (_, { id }) => {
      try {
        const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
        const user = await response.json();

        return {
          id: user.id,
          name: user.name,
          email: user.email,  // Return email instead of profilePicture
        };
      } catch (error) {
        throw new Error(`Failed to fetch user: ${error.message}`);
      }
    },
  },
};

module.exports = resolvers;
로그인 후 복사

사용자 쿼리 해석기는 REST API에서 데이터를 가져와 필수 필드만 반환합니다.

가짜 REST API에는 https://jsonplaceholder.typicode.com/을 사용합니다.

서버 설정

server.js 파일 만들기:

const { ApolloServer } = require('apollo-server');
const typeDefs = require('./schema');
const resolvers = require('./resolvers');

const server = new ApolloServer({
  typeDefs,
  resolvers,
});

server.listen({ port: 4000 }).then(({ url }) => {
  console.log(`GraphQL Server ready at ${url}`);
});
로그인 후 복사

서버 시작:

node server.js
로그인 후 복사

GraphQL 서버는 http://localhost:4000/graphql에 있으며 서버에 쿼리하면 이 페이지로 이동됩니다.

Enhancing React Applications with GraphQL Over REST APIs

React 애플리케이션과 통합

이제 GraphQL API를 사용하도록 React 애플리케이션을 변경하겠습니다.

Apollo 클라이언트 설치

npm install @apollo/client graphql
로그인 후 복사

Apollo 클라이언트 구성

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

const client = new ApolloClient({
  uri: 'http://localhost:4000', 
  cache: new InMemoryCache(),
});
로그인 후 복사

GraphQL 쿼리 작성

const GET_USER = gql`
  query GetUser($id: ID!) {
    user(id: $id) {
      id
      name
      email
    }
  }
`;
로그인 후 복사

이제 위의 코드 조각을 반응 앱에 통합하세요. 다음은 사용자가 userId를 선택하고 정보를 표시할 수 있는 간단한 반응 앱입니다.

import { useState } from 'react';
import { ApolloClient, InMemoryCache, ApolloProvider, gql, useQuery } from '@apollo/client';
import './App.css';  // Link to the updated CSS

const client = new ApolloClient({
  uri: 'http://localhost:4000',  // Ensure this is the correct URL for your GraphQL server
  cache: new InMemoryCache(),
});

const GET_USER = gql`
  query GetUser($id: ID!) {
    user(id: $id) {
      id
      name
      email
    }
  }
`;

const User = ({ userId }) => {
  const { loading, error, data } = useQuery(GET_USER, {
    variables: { id: userId },
  });

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <div className="user-container">
      <h2>{data.user.name}</h2>
      <p>Email: {data.user.email}</p>
    </div>
  );
};

const App = () => {
  const [selectedUserId, setSelectedUserId] = useState("1");

  return (
    <ApolloProvider client={client}>
      <div className="app-container">
        <h1 className="title">GraphQL User Lookup</h1>
        <div className="dropdown-container">
          <label htmlFor="userSelect">Select User ID:</label>
          <select
            id="userSelect"
            value={selectedUserId}
            onChange={(e) => setSelectedUserId(e.target.value)}
          >
            {Array.from({ length: 10 }, (_, index) => (
              <option key={index + 1} value={index + 1}>
                {index + 1}
              </option>
            ))}
          </select>
        </div>
        <User userId={selectedUserId} />
      </div>
    </ApolloProvider>
  );
};

export default App;
로그인 후 복사

결과:

단순 사용자

Enhancing React Applications with GraphQL Over REST APIs

Working with Multiple Endpoints

Imagine a scenario where you need to retrieve a specific user’s posts, along with the individual comments on each post. Instead of making three separate API calls from your frontend React app and dealing with unnecessary data, you can streamline the process with GraphQL. By defining a schema and crafting a GraphQL query, you can request only the exact data your UI requires, all in one efficient request.

We need to fetch user data, their posts, and comments for each post from the different endpoints. We’ll use fetch to gather data from the multiple endpoints and return it via GraphQL.

Update Resolvers

const fetch = require('node-fetch');

const resolvers = {
  Query: {
    user: async (_, { id }) => {
      try {
        // fetch user
        const userResponse = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
        const user = await userResponse.json();

        // fetch posts for a user
        const postsResponse = await fetch(`https://jsonplaceholder.typicode.com/posts?userId=${id}`);
        const posts = await postsResponse.json();

        // fetch comments for a post
        const postsWithComments = await Promise.all(
          posts.map(async (post) => {
            const commentsResponse = await fetch(`https://jsonplaceholder.typicode.com/comments?postId=${post.id}`);
            const comments = await commentsResponse.json();
            return { ...post, comments };
          })
        );

        return {
          id: user.id,
          name: user.name,
          email: user.email,
          posts: postsWithComments,
        };
      } catch (error) {
        throw new Error(`Failed to fetch user data: ${error.message}`);
      }
    },
  },
};

module.exports = resolvers;
로그인 후 복사

Update GraphQL Schema

const { gql } = require('apollo-server');

const typeDefs = gql`
  type Comment {
    id: ID!
    name: String
    email: String
    body: String
  }

  type Post {
    id: ID!
    title: String
    body: String
    comments: [Comment]
  }

  type User {
    id: ID!
    name: String
    email: String
    posts: [Post]
  }

  type Query {
    user(id: ID!): User
  }
`;

module.exports = typeDefs;
로그인 후 복사

Server setup in server.js remains same. Once we update the React.js code, we get the below output:

Detailed User

Enhancing React Applications with GraphQL Over REST APIs

Benefits of This Approach

Integrating GraphQL into your React application provides several advantages:

Eliminating Overfetching

A key feature of GraphQL is that it only fetches exactly what you request. The server only returns the requested fields and ensures that the amount of data transferred over the network is reduced by serving only what the query demands and thus improving performance.

Simplifying Frontend Code

GraphQL enables you to get the needful information in a single query regardless of their origin. Internally it could be making 3 API calls to get the information. This helps to simplify your frontend code because now you don’t need to orchestrate different async requests and combine their results.

Improving Developer’s Experience

A strong typing and schema introspection offer better tooling and error checking than in the traditional API implementation. Further to that, there are interactive environments where developers can build and test queries, including GraphiQL or Apollo Explorer.

Addressing Complexities and Challenges

This approach has some advantages but it also introduces some challenges that have to be managed.

Additional Backend Layer

The introduction of the GraphQL server creates an extra layer in your backend architecture and if not managed properly, it becomes a single point of failure.

Solution: Pay attention to error handling and monitoring. Containerization and orchestration tools like Docker and Kubernetes can help manage scalability and reliability.

Potential Performance Overhead

The GraphQL server may make multiple REST API calls to resolve a single query, which can introduce latency and overhead to the system.

Solution: Cache the results to avoid making several calls to the API. There exist some tools such as DataLoader which can handle the process of batching and caching of requests.

Conclusion

"Simplicity is the ultimate sophistication" — Leonardo da Vinci

Integrating GraphQL into your React application is more than just a performance optimization — it’s a strategic move towards building more maintainable, scalable, and efficient applications. By addressing overfetching and simplifying data management, you not only enhance the user experience but also empower your development team with better tools and practices.

While the introduction of a GraphQL layer comes with its own set of challenges, the benefits often outweigh the complexities. By carefully planning your implementation, optimizing your resolvers, and securing your endpoints, you can mitigate potential drawbacks. Moreover, the flexibility that GraphQL offers can future-proof your application as it grows and evolves.

Embracing GraphQL doesn’t mean abandoning your existing REST APIs. Instead, it allows you to leverage their strengths while providing a more efficient and flexible data access layer for your frontend applications. This hybrid approach combines the reliability of REST with the agility of GraphQL, giving you the best of both worlds.

If you’re ready to take your React application to the next level, consider integrating GraphQL into your data fetching strategy. The journey might present challenges, but the rewards — a smoother development process, happier developers, and satisfied users — make it a worthwhile endeavor.

Full Code Available

You can find the full code for this implementation on my GitHub repository: GitHub Link.

위 내용은 REST API를 통해 GraphQL을 사용하여 React 애플리케이션 향상의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!