如何设置GraphQL Express和PostgreSQL服务器

news/2024/7/9 20:47:15 标签: postgresql, python

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.

放一些示例数据,以更好地了解发生了什么。

Image for post
The database work!
数据库工作!

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”是将要传递的数据。

Image for post

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
Image for post
This gets all the users with ID 1.
这将获得所有ID为1的用户。

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


http://www.niftyadmin.cn/n/1468043.html

相关文章

python 没有控件_没有与Python Mechaniz名称匹配的控件

目前正在使用Mechanize提交一些表单这是我当前的代码片段:add_control br.form.find_control(nameCRN_IN, idcrn_id1)总共有10个文本框,我使用以下代码打印:^{pr2}$这是输出:如我的代码片段所示,我可以使用idcrn_id1选…

vue 虚拟dom_深入Vue 3s虚拟dom

vue 虚拟domIn this article, we do a dive into the virtual dom in Vue.js 3, and how we can traverse it with the goal of finding a specific component (or what we will call a vnode - more on this soon).在本文中,我们将深入研究Vue.js 3中的虚拟dom &am…

java递归解析xml_java-web-dom4j解析XML-递归方式

曾哥作者>东方不败作者>66.8售价>欲练此功,不必自宫!简介>辟邪剑谱书名>葵花宝典书名>书>九阴真经书名>独孤求败作者>88.9售价>武功狠!!!简介>书>书架>用递归将想找的标签名中的文本值找到:package myTestDom4j;…

您需要了解的关于React v17 0 Release候选的所有信息

Two years after launching React v16, the React team recently launched the first released candidate of React v17. Surprisingly, it doesn’t have any new features for developers. So what is v17? In this article, I will sum up all the latest changes done in …

java环境变量和用户变量_环境变量和用户变量有什么区别?

搭建编译环境时为什么有时候要设置环境变量,而有时又设置用户变量?环境变量分为系统环境变量和用户环境变量。你所说的环境变量是指系统环境变量,对所有用户起作用而用户环境变量只对当前用户起作用。例如你要用java,那么你把java…

react优化_优化您的React体验

react优化React is one of (if not the most) popular JavaScript library. There are good reasons why React is so beloved among Javascript developers. For one, it prioritizes the UI (User Interface) part of a website; this includes any aspect that a user inter…

java中br.readline_java中br.readLine与 br.read的用法区别

read方法功能:读取单个字符。 返回:作为一个整数(其范围从 0 到 65535 (0x00-0xffff))读入的字符,如果已到达流末尾,则返回 -1 readLine方法功能:读取一个文本行。通过下列字符之一即可认为某行已终止:换行…

仅使用javascript将样机转换为代码

AI is the future and it’s going to take all our jobs. You’ve probably heard that quite a bit as Machine Learning systems replace more and more traditional, manual, and repetitive jobs. You’ll also hear cries of the inevitable loss of entry level program…