Home > Web Front-end > JS Tutorial > Explore GraphQL with Apollo & React: Build a Superhero Database

Explore GraphQL with Apollo & React: Build a Superhero Database

Joseph Gordon-Levitt
Release: 2025-02-14 09:31:12
Original
824 people have browsed it

Explore GraphQL with Apollo & React: Build a Superhero Database

Dive into the world of GraphQL and discover why it's generating so much excitement! This tutorial provides a clear explanation of GraphQL and offers hands-on experience.

First, let's address the core question: What is GraphQL? It's not some obscure calculator function; instead, it's a powerful query language (or more precisely, a query specification) for fetching data from diverse sources. Its key advantage? It retrieves only the necessary data in a single network request, eliminating the inefficiencies of traditional REST APIs.

This tutorial uses an Apollo server as the endpoint and a React app with the Apollo client to access the data. We'll start with the server.

Key Concepts:

  • GraphQL is a query language offering precise data retrieval in a single request from any data source, surpassing REST APIs in efficiency and flexibility.
  • An Apollo server (endpoint) and a React app using the Apollo client are essential for GraphQL data utilization.
  • The tutorial illustrates schema creation, data addition, resolver definition, and integration, using a superhero database example.
  • It showcases how front-end and back-end development can proceed largely independently, with the schema acting as the interface.

Setting up the Apollo Server:

  1. Create an apollo-server directory.
  2. Navigate to it and install the necessary packages:
npm install apollo-server apollo-server-express graphql
Copy after login
Copy after login
  1. Create index.js and add:
const { ApolloServer, gql } = require('apollo-server');
Copy after login
Copy after login

This imports the essential components for the Apollo server and GraphQL query parsing.

Creating the GraphQL Schema:

Next, define the schema in index.js:

const typeDefs = gql`
  type User {
    id: ID!
    name: String
    superpowers: [Superpower]!
  }

  type Superpower {
    id: ID!
    text: String
  }

  type Query {
    users: [User]
    user(id: ID!): User
  }
`;
Copy after login
Copy after login

This defines User and Superpower types and two queries: users (returns all users) and user (returns a user by ID).

Adding Sample Data:

Add mock data to index.js:

const users = [
  { id: '1', name: 'Peter Parker', superpowers: [{ id: '1', text: 'Web slinging' }, { id: '2', text: 'Spidey sense' }] },
  { id: '2', name: 'Tony Stark', superpowers: [{ id: '3', text: 'Industrial design' }, { id: '4', text: 'Robotic fashion' }] }
];
Copy after login
Copy after login

This provides sample data for querying. Remember, GraphQL isn't limited to JavaScript arrays; it can connect to any data source.

Defining Resolvers:

Resolvers interpret the queries. Add these to index.js:

const resolvers = {
  Query: {
    users: () => users,
    user: (root, { id }) => users.find(user => user.id === id),
  },
};
Copy after login
Copy after login

The users resolver returns all users, while user finds a user by ID.

Starting the Server:

Complete index.js by instantiating and starting the server:

const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => console.log(`Apollo server started at ${url}`));
Copy after login
Copy after login

Run node index.js and access the GraphQL playground at http://localhost:4000/.

Interactive Queries:

Try these queries in the playground:

  • Fetch Peter Parker's name:
npm install apollo-server apollo-server-express graphql
Copy after login
Copy after login
  • Fetch Peter Parker's name and superpowers:
const { ApolloServer, gql } = require('apollo-server');
Copy after login
Copy after login
  • Fetch all users and their superpowers:
const typeDefs = gql`
  type User {
    id: ID!
    name: String
    superpowers: [Superpower]!
  }

  type Superpower {
    id: ID!
    text: String
  }

  type Query {
    users: [User]
    user(id: ID!): User
  }
`;
Copy after login
Copy after login

Integrating with React:

  1. Create a React app:
const users = [
  { id: '1', name: 'Peter Parker', superpowers: [{ id: '1', text: 'Web slinging' }, { id: '2', text: 'Spidey sense' }] },
  { id: '2', name: 'Tony Stark', superpowers: [{ id: '3', text: 'Industrial design' }, { id: '4', text: 'Robotic fashion' }] }
];
Copy after login
Copy after login
  1. Modify src/index.js:
const resolvers = {
  Query: {
    users: () => users,
    user: (root, { id }) => users.find(user => user.id === id),
  },
};
Copy after login
Copy after login
  1. Replace src/App.js:
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => console.log(`Apollo server started at ${url}`));
Copy after login
Copy after login

Run npm start in the my-graphql directory to see the results at http://localhost:3000/.

This tutorial provides a foundation for using GraphQL. Explore mutations (for data modification) and other advanced features to further enhance your skills. Happy coding!

GraphQL FAQs:

  • What is GraphQL? A query language for APIs and a runtime for executing those queries against your data. It's a more efficient and flexible alternative to REST.

  • GraphQL vs. REST: REST uses multiple endpoints, while GraphQL allows clients to request only the needed data in a single query, preventing over-fetching and under-fetching.

  • Key GraphQL Features: Hierarchical query structure, strong typing, real-time data with subscriptions, and introspection (querying the schema itself).

  • GraphQL Schema: Defines the data types and relationships, acting as a contract between client and server.

  • Query Structure: Hierarchical, mirroring the response data structure. Clients request specific fields and nest them for complex data retrieval.

  • Resolvers: Functions that define how to fetch or mutate data for specific schema fields. They connect the queries to the data source.

The above is the detailed content of Explore GraphQL with Apollo & React: Build a Superhero Database. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template