如何在Node.js实现GraphQL?


它基本上是API的查询语言,GraphQL显示了服务器提供的不同类型的数据,然后客户端可以准确地选择它想要的内容。同样在GraphQL中,您可以在一次调用中获取多个服务器资源,而不是进行多个REST API调用。
GraphQL可以与多种语言一起使用。在这里,我们将重点介绍如何使用NodeJS将JavaScript与JavaScript一起使用。

安装
创建一个名为graphql-with-nodejs的文件夹。进入项目文件夹并运行npm init以创建NodeJS项目。对此的命令如下。

cd graphql-with-nodejs
npm init

安装依赖项
使用以下命令安装Express:

npm install express

使用以下命令安装GraphQL。我们将安装graphql和graphql for express。

npm install express-graphql graphql

NodeJS代码
在项目中创建一个名为server.js的文件,并将以下代码复制到其中:

const express = require('express');
const port = 5000;
const app = express();

app.get('/hello', (req,res) => {
    res.send("hello");
   }
);

app.listen(port);
console.log(`Server Running at localhost:${port}`);


上面的代码有一个名为/ hello的 http get端点。
端点是使用express创建的。
现在让我们修改此代码以启用GraphQL。

在代码中启用GraphQL
GraphQL将有一个名为/ graphql的 url端点,它将处理所有请求。
将以下代码复制到server.js中

//get all the libraries needed
const express = require('express');
const graphqlHTTP = require('express-graphql');
const {GraphQLSchema} = require('graphql');

const {queryType} = require('./query.js');

//setting up the port number and express app
const port = 5000;
const app = express();

 
// Define the Schema
const schema = new GraphQLSchema({ query: queryType });

//Setup the nodejs GraphQL server
app.use('/graphql', graphqlHTTP({
    schema: schema,
    graphiql: true,
}));

app.listen(port);
console.log(`GraphQL Server Running at localhost:${port}`);

graphqlHTTP使我们能够在/ graphql url 上设置GraphQL服务器。它基本上知道如何处理即将发出的请求。此设置在以下代码行中完成:

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

现在让我们探索graphqlHTTP中的参数:

1. graphiql
graphiql是一个Web UI,您可以使用它来测试graphql端点。我们将其设置为true,以便更容易测试我们创建的各种graphql端点。

2.shcema
虽然graphql只有一个外部端点/ graphql,但这又可以让多个其他端点执行各种操作。这些端点将在shcema中指定。

shcema将执行以下操作:

  • 指定端点
  • 指示端点的输入和输出字段
  • 指示在命中端点时应执行的操作,依此类推。

Schema在代码中定义如下

const schema = new GraphQLSchema({ query: queryType });

3.query
在模式中可以看到查询已设置为queryType。我们使用以下命令从query.js文件导入queryType
const {queryType} = require('./query.js');

query.js是一个我们即将创建的自定义文件。
query是我们在模式中指定只读端点的地方。
在项目中创建一个名为query.js的文件,并将以下代码复制到其中。

const { GraphQLObjectType,
    GraphQLString
} = require('graphql');


//Define the Query
const queryType = new GraphQLObjectType({
    name: 'Query',
    fields: {
        hello: {
            type: GraphQLString,

            resolve: function () {
                return
"Hello World";
            }
        }
    }
});

exports.queryType = queryType;

queryType创建为GraphQLObjectType并命名为Query。
fields是我们指定各种端点的地方。
所以我们在这里添加一个名为hello的端点
hello world的GraphQLString意味着此端点具有字符串返回类型。因为这是graphql架构,所以类型是GraphQLString而不是String。所以直接使用String是行不通的。
resolve function表示调用端点时要执行的操作。这里的操作是返回一个字符串“Hello World”。
最后我们使用导出querytype exports.queryType = queryType。这是为了确保我们可以在server.js中导入它

运行:
node server.js

该应用程序在localhost:5000 / graphql上运行。
您可以转到localhost:5000 / graphql来测试应用程序。

您已经创建了第一个GraphQL端点。

github仓库中提供了此应用程序的完整代码