Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade For Teachers Spaces Get Certified Upgrade For Teachers Spaces
   ❮     
     ❯   

Node.js Tutorial

Node HOMENode IntroNode Get StartedNode JS RequirementsNode.js vs BrowserNode Cmd LineNode V8 EngineNode ArchitectureNode Event Loop

Asynchronous

Node AsyncNode PromisesNode Async/AwaitNode Errors Handling

Module Basics

Node ModulesNode ES ModulesNode NPMNode package.jsonNode NPM ScriptsNode Manage DepNode Publish Packages

Core Modules

HTTP ModuleHTTPS ModuleFile System (fs)Path ModuleOS ModuleURL ModuleEvents ModuleStream ModuleBuffer ModuleCrypto ModuleTimers ModuleDNS ModuleAssert ModuleUtil ModuleReadline Module

JS & TS Features

Node ES6+Node ProcessNode TypeScriptNode Adv. TypeScriptNode Lint & Formatting

Building Applications

Node FrameworksExpress.jsMiddleware ConceptREST API DesignAPI AuthenticationNode.js with Frontend

Database Integration

MySQL Get StartedMySQL Create DatabaseMySQL Create TableMySQL Insert IntoMySQL Select FromMySQL WhereMySQL Order ByMySQL DeleteMySQL Drop TableMySQL UpdateMySQL LimitMySQL Join
MongoDB Get StartedMongoDB Create DBMongoDB CollectionMongoDB InsertMongoDB FindMongoDB QueryMongoDB SortMongoDB DeleteMongoDB Drop CollectionMongoDB UpdateMongoDB LimitMongoDB Join

Advanced Communication

GraphQLSocket.IOWebSockets

Testing & Debugging

Node Adv. DebuggingNode Testing AppsNode Test FrameworksNode Test Runner

Node.js Deployment

Node Env VariablesNode Dev vs ProdNode CI/CDNode SecurityNode Deployment

Perfomance & Scaling

Node LoggingNode MonitoringNode PerformanceChild Process ModuleCluster ModuleWorker Threads

Node.js Advanced

MicroservicesNode WebAssemblyHTTP2 ModulePerf_hooks ModuleVM ModuleTLS/SSL ModuleNet ModuleZlib ModuleReal-World Examples

Hardware & IoT

RasPi Get StartedRasPi GPIO IntroductionRasPi Blinking LEDRasPi LED & PushbuttonRasPi Flowing LEDsRasPi WebSocketRasPi RGB LED WebSocketRasPi Components

Node.js Reference

Built-in ModulesEventEmitter (events)Worker (cluster)Cipher (crypto)Decipher (crypto)DiffieHellman (crypto)ECDH (crypto)Hash (crypto)Hmac (crypto)Sign (crypto)Verify (crypto)Socket (dgram, net, tls)ReadStream (fs, stream)WriteStream (fs, stream)Server (http, https, net, tls)Agent (http, https)Request (http)Response (http)Message (http)Interface (readline)

Resources & Tools

Node.js CompilerNode.js ServerNode.js QuizNode.js ExercisesNode.js SyllabusNode.js Study PlanNode.js Certificate

Node.jsGraphQL


What is GraphQL?

GraphQL is a query language for APIs and a runtime for executing those queries against your data. It was developed by Facebook in 2012 and publicly released in 2015.

Key Features

  • Client-specified queries: Request exactly what you need, nothing more
  • Single endpoint: Access all resources through one endpoint
  • Strongly typed: Clear schema defines available data and operations
  • Hierarchical: Queries match the shape of your data
  • Self-documenting: Schema serves as documentation

Note: Unlike REST, GraphQL lets clients specify exactly what data they need, reducing over-fetching and under-fetching of data.


Getting Started with GraphQL in Node.js

Prerequisites

  • Node.js installed (v14 or later recommended)
  • Basic knowledge of JavaScript and Node.js
  • npm or yarn package manager

Step 1: Set Up a New Project

Create a new directory and initialize a Node.js project:

mkdir graphql-server
cd graphql-server
npm init -y

Step 2: Install Required Packages

Install the necessary dependencies:

npm install express express-graphql graphql

This installs:

  • express: Web framework for Node.js
  • express-graphql: Middleware for creating a GraphQL HTTP server
  • graphql: The JavaScript reference implementation of GraphQL

Step 3: Create a Basic GraphQL Server

3.1 Define Your Data Model

Create a new fileserver.js and start by defining your data model using GraphQL's Schema Definition Language (SDL):

const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');

// Sample data
const books = [
  {
    id: '1',
    title: 'The Great Gatsby',
    author: 'F. Scott Fitzgerald',
    year: 1925,
    genre: 'Novel'
  },
  {
    id: '2',
    title: 'To Kill a Mockingbird',
    author: 'Harper Lee',
    year: 1960,
    genre: 'Southern Gothic'
  }
];

3.2 Define the GraphQL Schema

Add the schema definition to yourserver.js file:

// Define the schema using GraphQL schema language
const schema = buildSchema(`
  # A book has a title, author, and publication year
  type Book {
    id: ID!
    title: String!
    author: String!
    year: Int
    genre: String
  }

  # The "Query" type is the root of all GraphQL queries
  type Query {
    # Get all books
    books: [Book!]!
    # Get a specific book by ID
    book(id: ID!): Book
    # Search books by title or author
    searchBooks(query: String!): [Book!]!
  }
`);

3.3 Implement Resolvers

Add resolver functions to fetch the actual data:

// Define resolvers for the schema fields
const root = {
  // Resolver for fetching all books
  books: () => books,
  
  // Resolver for fetching a single book by ID
  book: ({ id }) => books.find(book => book.id === id),
  
  // Resolver for searching books
  searchBooks: ({ query }) => {
    const searchTerm = query.toLowerCase();
    return books.filter(
      book =>
        book.title.toLowerCase().includes(searchTerm) ||
        book.author.toLowerCase().includes(searchTerm)
    );
  }
};

3.4 Set Up the Express Server

Complete the server setup:

// Create an Express app
const app = express();

// Set up the GraphQL endpoint
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  // Enable the GraphiQL interface for testing
  graphiql: true,
}));

// Start the server
const PORT = 4000;
app.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}/graphql`);
});

Step 4: Run and Test Your GraphQL Server

4.1 Start the Server

Run your server with Node.js:

node server.js

You should see the message:Server running at http://localhost:4000/graphql

4.2 Test with GraphiQL

Open your browser and navigate tohttp://localhost:4000/graphql to access the GraphiQL interface.

Example Query: Get All Books
{
  books {
    id
    title
    author
    year
  }
}
Example Query: Get a Single Book
{
  book(id: "1") {
    title
    author
    genre
  }
}
Example Query: Search Books
{
  searchBooks(query: "Gatsby") {
    title
    author
    year
  }
}

Handling Mutations

Mutations are used to modify data on the server. Let's add the ability to add, update, and delete books.

1. Update the Schema

Add the Mutation type to your schema:

const schema = buildSchema(`
  # ... (previous types remain the same) ...

  # Input type for adding/updating books
  input BookInput {
    title: String
    author: String
    year: Int
    genre: String
  }

  type Mutation {
    # Add a new book
    addBook(input: BookInput!): Book!
    # Update an existing book
    updateBook(id: ID!, input: BookInput!): Book
    # Delete a book
    deleteBook(id: ID!): Boolean
  }
`);

2. Implement Mutation Resolvers

Update your root resolver object to include the mutation resolvers:

const root = {
  // ... (previous query resolvers remain the same) ...

  // Mutation resolvers
  addBook: ({ input }) => {
    const newBook = {
      id: String(books.length + 1),
      ...input
    }
    books.push(newBook);
    return newBook;
  },

  updateBook: ({ id, input }) => {
    const bookIndex = books.findIndex(book => book.id === id);
    if (bookIndex === -1) return null;

    const updatedBook = {
      ...books[bookIndex],
      ...input
    }
    books[bookIndex] = updatedBook;
    return updatedBook;
  },

  deleteBook: ({ id }) => {
    const bookIndex = books.findIndex(book => book.id === id);
    if (bookIndex === -1) return false;

    books.splice(bookIndex, 1);
    return true;
  }
};

3. Testing Mutations

Add a New Book

mutation {
  addBook(input: {
    title: "1984"
    author: "George Orwell"
    year: 1949
    genre: "Dystopian"
  }) {
    id
    title
    author
  }
}

Update a Book

mutation {
  updateBook(
    id: "1"
    input: { year: 1926 }
  ) {
    title
    year
  }
}

Delete a Book

mutation {
  deleteBook(id: "2")
}

Best Practices

1. Error Handling

Always handle errors properly in your resolvers:

const root = {
  book: ({ id }) => {
    const book = books.find(book => book.id === id);
    if (!book) {
      throw new Error('Book not found');
    }
    return book;
  },
  // ... other resolvers
}

2. Data Validation

Validate input data before processing:

const { GraphQLError } = require('graphql');

const root = {
  addBook: ({ input }) => {
    if (input.year && (input.year < 0 || input.year > new Date().getFullYear() + 1)) {
      throw new GraphQLError('Invalid publication year', {
        extensions: { code: 'BAD_USER_INPUT' }
      }
    }
    // ... rest of the resolver
  }
};

3. N+1 Problem

Use DataLoader to batch and cache database queries:

npm install dataloader
const DataLoader = require('dataloader');

// Create a loader for books
const bookLoader = new DataLoader(async (ids) => {
  // This would be a database query in a real app
  return ids.map(id => books.find(book => book.id === id));
});

const root = {
  book: ({ id }) => bookLoader.load(id),
  // ... other resolvers
};

Next Steps

  • Connect to a real database (MongoDB, PostgreSQL, etc.)
  • Implement authentication and authorization
  • Add subscriptions for real-time updates
  • Explore Apollo Server for more advanced features
  • Learn about schema stitching and federation for microservices

Tip: Always use variables in your GraphQL operations for better reusability and security.


GraphQL Schemas and Types

GraphQL schemas define the structure of your API and the types of data that can be requested.

Type System

GraphQL uses a type system to define the shape of your data. Here are the basic scalar types:

TypeDescriptionExample
IntSigned 32-bit integer42
FloatSigned double-precision floating-point value3.14
StringUTF-8 character sequence"Hello, GraphQL!"
Booleantrue or falsetrue,false
IDUnique identifier, serialized as a String"5f8a8d8e8f8c8d8b8a8e8f8c"




×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookies andprivacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.


[8]ページ先頭

©2009-2025 Movatter.jp