头图

[Note] This section is translated from: GraphQL-Quick Guide (tutorialspoint.com)

In this chapter, we will learn about the environment settings of GraphQL. To perform the examples in this tutorial, you will need the following:

  • A computer running Linux, macOS, or Windows.
  • Web browser, preferably the latest version of Google Chrome.
  • The latest version of Node.js is installed. It is recommended to use the latest LTS version.
  • Visual Studio Code or any code editor of your choice is installed for VSCode's extended GraphQL.

How to use Nodejs to build a GraphQL server

We will introduce in detail the steps to build a GraphQL server using Nodejs, as follows:

Step 1-Verify node and Npm version

After installing NodeJs, use the following command on the terminal to verify the version of node and npm:

C:\Users\Admin>node -v
v8.11.3

C:\Users\Admin>npm -v
5.6.0

Step 2-Create a project folder and open the root folder of the project in VSCode can be named test-app.

Follow the instructions below to open the folder using the Visual Studio Code Editor:

C:\Users\Admin>mkdir test-app
C:\Users\Admin>cd test-app
C:\Users\Admin\test-app>code.

Step 3-Create package.json and install dependencies

Create a package.json file, which will contain all the dependencies of the GraphQL server application.

{
   "name": "hello-world-server",
   "private": true,
   "scripts": {
      "start": "nodemon --ignore data/ server.js"
   },
   "dependencies": {
      "apollo-server-express": "^1.4.0",
      "body-parser": "^1.18.3",
      "cors": "^2.8.4",
      "express": "^4.16.3",
      "graphql": "^0.13.2",
      "graphql-tools": "^3.1.1"
   },
   "devDependencies": {
      "nodemon": "1.17.1"
   }
}

Install the dependencies using the command given below:

C:\Users\Admin\test-app>npm install

Step 4-Create a flat file database in the data folder

In this step, we use flat files to store and retrieve data. Create a folder data and add two files student.json and Colleges.json .
The following is the Colleges.json file:

[
    {
       "id": "col-101",
       "name": "AMU",
       "location": "Uttar Pradesh",
       "rating":5.0
    },
    
    {
       "id": "col-102",
       "name": "CUSAT",
       "location": "Kerala",
       "rating":4.5
    }
 ]

The following is the student.json file:

[
    {
       "id": "S1001",
       "firstName":"Mohtashim",
       "lastName":"Mohammad",
       "email": "mohtashim.mohammad@tutorialpoint.org",
       "password": "pass123",
       "collegeId": "col-102"
    },
    
    {
       "id": "S1002",
       "email": "kannan.sudhakaran@tutorialpoint.org",
       "firstName":"Kannan",
       "lastName":"Sudhakaran",
       "password": "pass123",
       "collegeId": "col-101"
    },
    
    {
       "id": "S1003",
       "email": "kiran.panigrahi@tutorialpoint.org",
       "firstName":"Kiran",
       "lastName":"Panigrahi",
       "password": "pass123",
       "collegeId": "col-101"
    }
 ]

Step 5-Create the data access layer

We need to create a data store that loads the contents of the data folder. In this case, we need to set variables, students, and universities. Whenever the application needs data, it will use these collection variables.
Create the file db.js in the project folder as follows:

const { DataStore } = require('notarealdb');

const store = new DataStore('./data');

module.exports = {
   students:store.collection('students'),
   colleges:store.collection('colleges')
};

Step 6-Create the schema file, schema.graphql

Create a pattern file in the current project folder and add the following content:

type Query  {
   test: String
}

Step 7-Create the resolver file, resolvers.js

Create a parser file in the current project folder and add the following content:

const Query = {
    test: () => 'Test Success, GraphQL server is up & running !!'
 }
 module.exports = {Query}

Step 8-Create Server.js and configure GraphQL

Create a server file and configure GraphQL as follows:

const bodyParser = require('body-parser');
const cors = require('cors');
const express = require('express');
const db = require('./db');

const port = process.env.PORT || 9000;
const app = express();

const fs = require('fs')
const typeDefs = fs.readFileSync('./schema.graphql',{encoding:'utf-8'})
const resolvers = require('./resolvers')

const {makeExecutableSchema} = require('graphql-tools')
const schema = makeExecutableSchema({typeDefs, resolvers})

app.use(cors(), bodyParser.json());

const  {graphiqlExpress,graphqlExpress} = require('apollo-server-express')
app.use('/graphql',graphqlExpress({schema}))
app.use('/graphiql',graphiqlExpress({endpointURL:'/graphql'}))

app.listen(
   port, () => console.info(
      `Server started on port ${port}`
   )
);

Step 9-Run the application and test it with GraphiQL

The folder structure of the verification project test-app is as follows:

test-app /
   -->package.json
   -->db.js
   -->data
      students.json
      colleges.json
   -->resolvers.js
   -->schema.graphql
   -->server.js

Run the command npm start as follows:

C:\Users\Admin\test-app>npm start

The server is running on port 9000, so we can use the GraphiQL tool to test the application. Open the browser and enter the URL http://localhost:9000/graphiql . Enter the following query in the editor:

{
  test
}

The response from the server is as follows:

{
    "data": {
        "test": "Test Success, GraphQL server is running !!"
    }
}


信码由缰
65 声望8 粉丝

“码”界老兵,分享程序人生。


引用和评论

0 条评论