Meningkatkan Aplikasi React dengan GraphQL Daripada REST API

Mary-Kate Olsen
Lepaskan: 2024-10-03 14:26:31
asal
549 orang telah melayarinya

Dalam dunia pembangunan web yang pesat berubah, pengoptimuman dan penskalaan aplikasi sentiasa menjadi isu. React.js mempunyai kejayaan yang luar biasa untuk pembangunan frontend sebagai alat, yang menyediakan cara yang mantap untuk mencipta antara muka pengguna. Tetapi ia menjadi rumit dengan aplikasi yang semakin berkembang, terutamanya apabila ia melibatkan berbilang titik akhir REST API. Kebimbangan seperti pengambilan berlebihan, apabila data yang berlebihan daripada yang diperlukan boleh menjadi sumber kesesakan prestasi dan pengalaman pengguna yang buruk.

Antara penyelesaian kepada cabaran ini ialah mengguna pakai penggunaan GraphQL dengan aplikasi React. Jika bahagian belakang anda mempunyai berbilang titik akhir REST, maka memperkenalkan lapisan GraphQL yang secara dalaman memanggil titik akhir REST API anda boleh meningkatkan aplikasi anda daripada mengambil secara berlebihan dan menyelaraskan aplikasi bahagian hadapan anda. Dalam artikel ini, anda akan mendapati cara menggunakannya, kelebihan dan kekurangan pendekatan ini, pelbagai cabaran; dan cara menanganinya. Kami juga akan menyelam lebih dalam beberapa contoh praktikal tentang cara GraphQL boleh membantu anda memperbaik cara anda bekerja dengan data anda.

Pengambilan berlebihan dalam REST API

Dalam API REST, Pengambilan berlebihan berlaku apabila jumlah data yang dihantar oleh API kepada pelanggan adalah lebih daripada yang diperlukan oleh pelanggan. Ini adalah masalah biasa dengan API REST, yang sering mengembalikan Objek atau Skema Respons tetap. Untuk lebih memahami masalah ini, mari kita pertimbangkan satu contoh.

Pertimbangkan halaman profil pengguna di mana ia hanya diperlukan untuk menunjukkan nama dan e-mel pengguna. Dengan API REST biasa, pengambilan data pengguna mungkin kelihatan seperti ini:

fetch('/api/users/1')
  .then(response => response.json())
  .then(user => {
    // Use the user's name and profilePicture in the UI
  });
Salin selepas log masuk

Respons API akan termasuk data yang tidak diperlukan:

{
  "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
}
Salin selepas log masuk

Walaupun aplikasi hanya memerlukan nama dan medan e-mel pengguna, API mengembalikan keseluruhan objek pengguna. Data tambahan ini selalunya meningkatkan saiz muatan, mengambil lebih lebar jalur dan akhirnya boleh melambatkan aplikasi apabila digunakan pada peranti dengan sumber terhad atau sambungan rangkaian yang perlahan.

GraphQL sebagai Penyelesaian

GraphQL menangani masalah overfetching dengan membenarkan pelanggan meminta data yang mereka perlukan dengan tepat. Dengan menyepadukan pelayan GraphQL ke dalam aplikasi anda, anda boleh mencipta lapisan pengambilan data yang fleksibel dan cekap yang berkomunikasi dengan API REST sedia ada anda.

Bagaimana Ia Berfungsi

  1. Persediaan Pelayan GraphQL: Anda memperkenalkan pelayan GraphQL yang berfungsi sebagai perantara antara bahagian hadapan React anda dan API REST.
  2. Definisi Skema: Anda mentakrifkan skema GraphQL yang menentukan jenis data dan pertanyaan bahagian hadapan anda.
  3. Pelaksanaan Penyelesai: Anda melaksanakan penyelesai dalam pelayan GraphQL yang mengambil data daripada API REST dan hanya mengembalikan medan yang diperlukan.
  4. Integrasi Depan: Anda mengemas kini aplikasi React anda untuk menggunakan pertanyaan GraphQL dan bukannya panggilan API REST terus.

Pendekatan ini membolehkan anda mengoptimumkan pengambilan data tanpa merombak infrastruktur bahagian belakang sedia ada anda.

Melaksanakan GraphQL dalam Aplikasi React

Mari lihat cara menyediakan pelayan GraphQL dan menyepadukannya ke dalam aplikasi React.

Pasang Ketergantungan:

npm install apollo-server graphql axios
Salin selepas log masuk

Tentukan Skema

Buat fail bernama 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;
Salin selepas log masuk

Skema ini mentakrifkan jenis Pengguna dan pertanyaan pengguna yang mengambil pengguna melalui ID.

Laksanakan Penyelesai

Buat fail yang dipanggil 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;
Salin selepas log masuk

Penyelesai untuk pertanyaan pengguna mengambil data daripada REST API dan hanya mengembalikan medan yang diperlukan.

Kami akan menggunakan https://jsonplaceholder.typicode.com/untuk API REST palsu kami.

Sediakan Pelayan

Buat fail 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}`);
});
Salin selepas log masuk

Mulakan pelayan:

node server.js
Salin selepas log masuk

Pelayan GraphQL anda disiarkan secara langsung di http://localhost:4000/graphql dan jika anda menanyakan pelayan anda, ia akan membawa anda ke halaman ini.

Enhancing React Applications with GraphQL Over REST APIs

Mengintegrasikan dengan Aplikasi React

Kami kini akan menukar aplikasi React untuk menggunakan API GraphQL.

Pasang Pelanggan Apollo

npm install @apollo/client graphql
Salin selepas log masuk

Konfigurasikan Pelanggan Apollo

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

const client = new ApolloClient({
  uri: 'http://localhost:4000', 
  cache: new InMemoryCache(),
});
Salin selepas log masuk

Tulis Pertanyaan GraphQL

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

Sekarang sepadukan kepingan kod di atas dengan apl reaksi anda. Berikut ialah apl reaksi mudah di bawah yang membolehkan pengguna memilih ID pengguna dan memaparkan maklumat:

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;
Salin selepas log masuk

Keputusan:

Pengguna Mudah

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;
Salin selepas log masuk

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;
Salin selepas log masuk

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.

Atas ialah kandungan terperinci Meningkatkan Aplikasi React dengan GraphQL Daripada REST API. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!