What is GraphQL?
什么是GraphQL?
GraphQL is a middleware that allows the user to have 1 endpoint to handle most requests on your express server. The benefits of using this:
GraphQL是一种中间件,它允许用户有1个端点来处理您的快速服务器上的大多数请求。 使用此方法的好处:
- Avoids having to create many routes to handle everything. 避免创建许多路由来处理所有事情。
- Avoids over-fetching and under-fetching data 避免过度提取和提取不足的数据
- This works concurrently with API routes so the server can still be RESTful. 这与API路由同时工作,因此服务器仍可以是RESTful的。
Install devDependencies
安装devDependencies
When this was written keywords import and export were not supported fully so this step is recommended.
撰写本文时,不完全支持关键字导入和导出,因此建议执行此步骤。
npm install @babel/core @babel/node @babel/preset-env nodemon --save-dev
Setting Up The Express Server
设置Express服务器
First thing to do is install express and make a index.js file.
首先要做的是安装express并制作一个index.js文件。
npm install express
This server will be using the Hello world example from the express documentation but with some small changes to incorporate import.
该服务器将使用快速文档中的Hello world示例,但需要进行一些小的更改以合并导入。
import express from 'express'
const app = express()
const port = 3000app.get('/', (req, res) => {
res.send('Hello World!')
})app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
The simple server is up and running here and needs sequelize models.
简单的服务器已在此处启动并运行,并且需要序列化模型。
Setting Up Models with Seqeulize
使用Seqeulize设置模型
Create a postgreSQL database using the below command, this server’s database will be called medium.
使用以下命令创建一个postgreSQL数据库,该服务器的数据库将被称为medium。
createdb medium
Install sequelize and its drivers. Sequelize will convert the javascript code into SQL but pg and pg-hstore communicate with postgreSQL and make the actual changes.
安装sequelize及其驱动程序。 Sequelize会将javascript代码转换为SQL,但是pg和pg-hstore与postgreSQL通信并进行实际更改。
npm install sequelize pg pg-hstore.
Create a new folder called database and a models folder inside that and a models.js file in that. Here the actual models will be made. Import sequelize and create a new instance of Sequelize passing in a string with the name of the database “postgres://localhost:5432/medium”
创建一个名为database的新文件夹,并在其中创建一个models文件夹,并在其中创建一个models.js文件。 在这里将创建实际模型。 导入sequelize并创建一个新的Sequelize实例,并传入一个字符串,其名称为数据库“ postgres:// localhost:5432 / medium”
import Sequelize from 'sequelize'const sequelize = new Sequelize(`postgres://localhost:5432/medium`)
On this same file create a model. In this example, a user model is created with only a firstName property that must be set to valid because allowNull is set to false. Each property must have a Sequelize type. More Seqeulize types can be found in the Sequelize documentation. These datatypes ensure the information stored is of the same type.
在同一文件上创建一个模型。 在此示例中,仅使用firstName属性创建用户模型,该属性必须设置为有效,因为allowNull设置为false。 每个属性必须具有Sequelize类型。 在Sequelize文档中可以找到更多的Seqeulize类型。 这些数据类型可确保存储的信息属于同一类型。
Put some example data to have a better look at whats going on.
放一些示例数据,以更好地了解发生了什么。
Export this database so it can be used for the graphQL schemas.
导出此数据库,以便可以将其用于graphQL模式。
export default sequelize;
Setting Up GraphQL Schema
设置GraphQL模式
Inside the database folder create a schema folder and in there create a schema.js file. Import the sequelize file.
在数据库文件夹中创建一个schema文件夹,然后在其中创建一个schema.js文件。 导入序列化文件。
import db from '../models/models'
There are special graphQL datatypes that will be needed. This example will use the ones below.
将需要特殊的graphQL数据类型。 本示例将使用以下示例。
import {GraphQLObjectType, GraphQLString, GraphQLInt, GraphQLSchema, GraphQLList, GraphQLNonNull } from 'graphql'
Since graphQL is a middleware, special graphQL objects are needed in order for graphQL to know what to do. For this example,
由于graphQL是中间件,因此需要特殊的graphQL对象才能使graphQL知道要做什么。 在这个例子中
The GraphQLObjectType that was created above is a graphQL schema for the Sequelize model that was made for the Users model above. Each field corresponds to a field in the Sequelize model and has a graphql type that dictates what the datatype should be. GraphQL handles the promise received from Sequelize when requests are made through the resolve function.
上面创建的GraphQLObjectType是为上面的Users模型制作的Sequelize模型的graphQL模式。 每个字段都对应于Sequelize模型中的一个字段,并具有graphql类型,该类型指示数据类型应为什么。 当通过resolve函数发出请求时,GraphQL处理从Sequelize接收到的Promise。
That is just the Schema for a user, to make a query a whole new GraphQLObjectType needs to be made. This one has some extra fields and the GraphQL datatype is GraphQLList(User) which refers to the schema that was made above. The resolve function also works a bit differently from the User Schema as it as a 2nd parameter, “args”. “args” is the data that will be passed in.
这只是用户的架构,要进行查询,需要创建一个全新的GraphQLObjectType。 这个有一些额外的字段,并且GraphQL数据类型是GraphQLList(User),它引用上面创建的架构。 resolve函数作为第二个参数“ args”,其功能与User Schema有所不同。 “ args”是将要传递的数据。
That is just for making a query. In order to make post requests a GraphQLObjectType called mutation needs to be made. This is similar to the query GraphQLObjectType but in it, changes to the database will be made.
那只是为了查询。 为了发出请求,需要创建一个称为mutation的GraphQLObjectType。 这与查询GraphQLObjectType相似,但是其中将对数据库进行更改。
Finally to connect it all together GraphQLSchema must be called and initialized with the Query and Mutation objects that were made. This Schema has to be exported to be connected in the index.js file.
最后,要将其全部连接在一起,必须调用GraphQLSchema并使用已创建的Query和Mutation对象进行初始化。 必须将该模式导出以在index.js文件中进行连接。
export default Schema
With all the schemas and models set up, the server is finally ready to use the middleware.
设置好所有模式和模型之后,服务器终于可以使用中间件了。
import { graphqlHTTP } from 'express-graphql'import Schema from './database/schema/schema'
Create a new express route passing the graphqlHTTP middleware. In this server, it will be ‘graphql’ route.
创建一个新的快速路由,通过graphqlHTTP中间件。 在此服务器中,它将是“ graphql”路由。
As mentioned earlier, graphQL and RESTful API’s can work concurrently so that the ‘/’ route still works.
如前所述,graphQL和RESTful API可以同时工作,因此“ /”路由仍然有效。
To test the ‘/graphql’ route npm install graphiql, an easy to use GUI to test queries then go to ‘http://localhost:3000/graphql’
要测试'/ graphql'路由npm,请安装graphiql(一种易于使用的GUI来测试查询),然后转到' http:// localhost:3000 / graphql '
npm install graphiql
Here is the github for anyone who wants the full code.
这是任何想要完整代码的人的github。
翻译自: https://medium.com/swlh/how-to-setup-a-graphql-express-and-postgresql-server-7ab2c0f6ddbd