Home > Web Front-end > Front-end Q&A > graphql nodejs query

graphql nodejs query

WBOY
Release: 2023-05-25 10:13:37
Original
619 people have browsed it

GraphQL is a query language that can be used to request data in APIs. It is a strongly typed query language that helps us define the fields that can be requested in the API and the type of each field. GraphQL was originally developed by Facebook and has since been open sourced and widely used to build web applications.

Node.js is a popular JavaScript runtime environment that allows us to write server-side applications using JavaScript. Node.js's efficiency and robust ecosystem make it ideal for building high-performance APIs. There are many GraphQL libraries in Node.js that make using GraphQL APIs very simple and efficient.

This article will introduce how to use GraphQL to query data in Node.js. We will use a simple application based on Node.js and the Express framework to query data using GraphQL.

Step One: Create a Simple Express Application and Configure GraphQL

First, we need to create a Node.js application. Let's use the Express framework to build our application. Before creating the application, make sure Node.js and npm are installed on your system. We can check whether Node.js is installed by entering the following command in the terminal:

node -v
Copy after login

If you have successfully installed Node.js, you should see the version number installed.

Next, create a new project directory in the terminal and initialize npm:

mkdir nodejs-graphql-demo
cd nodejs-graphql-demo
npm init -y
Copy after login

Now, let us install the necessary dependencies using the following command:

npm install express graphql express-graphql
Copy after login

In our Before proceeding, let us understand these dependencies in detail.

  • Express: Web application framework, which can help us build Web applications based on Node.js.
  • GraphQL: Query language, which can be used to request data in APIs.
  • express-graphql: GraphQL middleware for the Express framework.

Next, let us create a new file server.js in the project home directory and add the following content:

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

const app = express();

const schema = buildSchema(`
  type Query {
    message: String
  }
`);

const root = {
  message: () => 'Hello World!'
};

app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true
}));

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
Copy after login

In the above code, we first import Express, graphqlHTTP and buildSchema modules. Next, we create an Express instance and define a simple query schema using the buildSchema function. Our query pattern contains only one query field called message and returns a string.

Next, we define a JavaScript object named root, which contains a message function that returns "Hello World!" In GraphQL, this object is called the root resolver object. We define a middleware for GraphQL and use the schema and root resolver objects we just created. This middleware will provide a GraphQL service on the path routed to /graphql, and the graphiql option set to true will enable the GraphiQL interface.

Finally, we start the application using the listen method of the Express instance and listen on port 5000.

Step 2: Test the GraphQL query

We have successfully configured the GraphQL middleware and now we can test our query. Let's use Postman to do this. First, we need to install and start Postman. Start Postman by entering the following command in the terminal:

postman
Copy after login

Now, let us create a new POST request and set the URL to http://localhost:5000/graphql. In the request body, add the following query to the GraphQL query editor:

query {
  message
}
Copy after login

Now we can send the request and view the response. The response should contain the following:

{
    "data": {
        "message": "Hello World!"
    }
}
Copy after login

As you can see, we successfully got the response from the GraphQL query. Let's enhance our query with more query fields and types.

Step 3: Add more query fields and types

Now, let’s expand our query pattern to include more fields and types. Let’s take a look at the following example:

const schema = buildSchema(`
  type Query {
    message: String
    number: Int
    person: Person
  }

  type Person {
    name: String
    age: Int
    address: Address
  }

  type Address {
    street: String
    city: String
    state: String
    country: String
  }
`);

const root = {
  message: () => 'Hello World!',
  number: () => 42,
  person: () => ({
    name: 'John Doe',
    age: 30,
    address: { 
      street: '123 Main St',
      city: 'Anytown',
      state: 'CA',
      country: 'USA'
    }
  })
};
Copy after login

In the above code, we have added an integer query field called number, and a query field called person, which returns an object of type Person. We also define the Person and Address types.

In the root parser object, we define functions corresponding to the new fields and types. The message and number fields return strings and integers respectively, while the person field returns a Person object whose fields and values ​​are defined by us.

Now, let’s test the new query. We can use the following query:

query {
  message
  number
  person {
    name
    age
    address {
      street
      city
      state
      country
    }
  }
}
Copy after login

The response should contain the following:

{
  "data": {
    "message": "Hello World!",
    "number": 42,
    "person": {
      "name": "John Doe",
      "age": 30,
      "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "CA",
        "country": "USA"
      }
    }
  }
}
Copy after login

As you can see, we have successfully queried the new fields and types. You can add more fields and types as needed to return more useful data in the API.

Conclusion

In this article, we learned how to query data using GraphQL in Node.js. We created a simple application based on the Express framework and used Express middleware and the GraphQL module to query data programmatically. We've also added more query fields and types to enhance our queries. GraphQL is a very powerful and useful tool that helps us build efficient and scalable APIs.

The above is the detailed content of graphql nodejs query. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template