Maison > interface Web > js tutoriel > le corps du texte

Améliorer les applications React avec GraphQL sur les API REST

Mary-Kate Olsen
Libérer: 2024-10-03 14:26:31
original
556 Les gens l'ont consulté

Dans le monde en évolution rapide du développement Web, l'optimisation et la mise à l'échelle des applications sont toujours un problème. React.js a connu un succès extraordinaire pour le développement frontend en tant qu'outil offrant un moyen robuste de créer des interfaces utilisateur. Mais cela se complique avec la croissance des applications, en particulier lorsqu'il s'agit de plusieurs points de terminaison d'API REST. Des problèmes tels que la récupération excessive, où un excès de données par rapport à ce qui est requis peut être une source de goulot d'étranglement en termes de performances et d'une mauvaise expérience utilisateur.

Parmi les solutions à ces défis figure l'adoption de l'utilisation de GraphQL avec les applications React. Si votre backend dispose de plusieurs points de terminaison REST, l'introduction d'une couche GraphQL qui appelle en interne les points de terminaison de votre API REST peut améliorer votre application contre la surexploitation et rationaliser votre application frontend. Dans cet article, vous découvrirez comment l'utiliser, les avantages et les inconvénients de cette approche, divers enjeux ; et comment y répondre. Nous approfondirons également quelques exemples pratiques de la façon dont GraphQL peut vous aider à améliorer la façon dont vous travaillez avec vos données.

Surcharge dans les API REST

Dans les API REST, la surextraction se produit lorsque la quantité de données que l'API fournit au client est supérieure à ce dont le client a besoin. Il s'agit d'un problème courant avec les API REST, qui renvoient souvent un schéma d'objet ou de réponse fixe. Pour mieux comprendre ce problème, prenons un exemple.

Considérez une page de profil utilisateur où il suffit d'afficher le nom et l'adresse e-mail de l'utilisateur. Avec une API REST typique, la récupération des données utilisateur pourrait ressembler à ceci :

fetch('/api/users/1')
  .then(response => response.json())
  .then(user => {
    // Use the user's name and profilePicture in the UI
  });
Copier après la connexion

La réponse de l'API inclura des données inutiles :

{
  "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
}
Copier après la connexion

Bien que l'application ne nécessite que les champs nom et email de l'utilisateur, l'API renvoie l'intégralité de l'objet utilisateur. Ces données supplémentaires augmentent souvent la taille de la charge utile, consomment plus de bande passante et peuvent éventuellement ralentir l'application lorsqu'elles sont utilisées sur un appareil doté de ressources limitées ou d'une connexion réseau lente.

GraphQL comme solution

GraphQL résout le problème de surcharge en permettant aux clients de demander exactement les données dont ils ont besoin. En intégrant un serveur GraphQL dans votre application, vous pouvez créer une couche de récupération de données flexible et efficace qui communique avec vos API REST existantes.

Comment ça marche

  1. Configuration du serveur GraphQL : Vous introduisez un serveur GraphQL qui sert d'intermédiaire entre votre interface React et les API REST.
  2. Définition du schéma : vous définissez un schéma GraphQL qui spécifie les types de données et les requêtes requises par votre interface.
  3. Implémentation des résolveurs : vous implémentez des résolveurs dans le serveur GraphQL qui récupèrent les données des API REST et renvoient uniquement les champs nécessaires.
  4. Intégration frontend : vous mettez à jour votre application React pour utiliser des requêtes GraphQL au lieu d'appels directs à l'API REST.

Cette approche vous permet d'optimiser la récupération de données sans remanier votre infrastructure backend existante.

Implémentation de GraphQL dans une application React

Voyons comment configurer un serveur GraphQL et l'intégrer dans une application React.

Installer les dépendances :

npm install apollo-server graphql axios
Copier après la connexion

Définir le schéma

Créez un fichier appelé 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;
Copier après la connexion

Ce schéma définit un type d'utilisateur et une requête utilisateur qui récupère un utilisateur par ID.

Implémenter des résolveurs

Créez un fichier appelé résolveurs.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;
Copier après la connexion

Le résolveur de la requête utilisateur récupère les données de l'API REST et renvoie uniquement les champs obligatoires.

Nous utiliserons https://jsonplaceholder.typicode.com/pour notre fausse API REST.

Configurer le serveur

Créez un fichier 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}`);
});
Copier après la connexion

Démarrez le serveur :

node server.js
Copier après la connexion

Votre serveur GraphQL est en ligne sur http://localhost:4000/graphql et si vous interrogez votre serveur, il vous mènera à cette page.

Enhancing React Applications with GraphQL Over REST APIs

Intégration avec l'application React

Nous allons maintenant modifier l'application React pour utiliser l'API GraphQL.

Installer le client Apollo

npm install @apollo/client graphql
Copier après la connexion

Configurer le client Apollo

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

const client = new ApolloClient({
  uri: 'http://localhost:4000', 
  cache: new InMemoryCache(),
});
Copier après la connexion

Écrire la requête GraphQL

const GET_USER = gql`
  query GetUser($id: ID!) {
    user(id: $id) {
      id
      name
      email
    }
  }
`;
Copier après la connexion

Intégrez maintenant les morceaux de codes ci-dessus à votre application React. Voici une application de réaction simple ci-dessous qui permet à un utilisateur de sélectionner l'ID utilisateur et d'afficher les informations :

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;
Copier après la connexion

Résultat:

Utilisateur simple

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;
Copier après la connexion

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;
Copier après la connexion

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.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:dev.to
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!