如何使用Node.js,Express和MongoDB设置GraphQL服务器

by Leonardo Maldonado

莱昂纳多·马尔多纳多(Leonardo Maldonado)

如何使用Node.js,Express和MongoDB设置GraphQL服务器 (How to set up a GraphQL Server using Node.js, Express & MongoDB)

从GraphQL和MongoDB开始的最直接的方法。 (The most straightforward way to start with GraphQL & MongoDB.)

So you are planning to start with GraphQL and MongoDB. Then you realize how can I set up those two technologies together? Well, this article is made precisely for you. I’ll show you how to set up a GraphQL server using MongoDB. I will show you how you can modularize your GraphQL schema and all this using MLab as our database.

因此,您计划从GraphQL和MongoDB开始。 然后您意识到如何将这两种技术一起设置? 好吧,本文专为您而设计。 我将向您展示如何使用MongoDB设置GraphQL服务器。 我将向您展示如何使用MLab作为我们的数据库来模块化GraphQL模式以及所有这些。

All the code from this article is available here.

本文中的所有代码均在此处提供。

So now, let’s get started.

现在,让我们开始吧。

为什么选择GraphQL? (Why GraphQL?)

GraphQL is a query language for your APIs. It was released by Facebook back in 2015 and has gained a very high adoption. It’s the replacement of REST.

GraphQL是API的查询语言。 它于2015年由Facebook发布,并获得了很高的采用率。 它是REST的替代品

With GraphQL, the client can ask for the exact data that they need and get back exactly what they asked for. GraphQL also uses a JSON-like query syntax to make those requests. All requests go to the same endpoint.

借助GraphQL,客户可以要求他们提供所需的确切数据,然后准确地获取他们所要求的数据。 GraphQL还使用类似JSON的查询语法来发出这些请求。 所有请求都到达相同的端点。

If you’re reading this article, I assume that you know a little bit about GraphQL. If you don’t know, you can learn more about GraphQL here.

如果您正在阅读本文,我假设您对GraphQL有所了解。 如果您不知道,可以在这里了解有关GraphQL的更多信息

入门 (Getting started)

First, create a folder, then start our project.

首先,创建一个文件夹,然后启动我们的项目。

npm init -y

Then install some dependencies for our project.

然后为我们的项目安装一些依赖项。

npm install @babel/cli @babel/core @babel/preset-env body-parser concurrently cors express express-graphql graphql graphql-tools merge-graphql-schemas mongoose nodemon

And then @babel/node as a dev dependency:

然后@ babel / node作为dev依赖项:

npm install --save-dev @babel/node
巴别塔 (Babel)

Now we’re gonna set up Babel for our project. Create a file called .babelrc in your project folder. Then, put the @babel/env there, like this:

现在我们将为我们的项目设置Babel。 在项目文件夹中创建一个名为.babelrc的文件。 然后,将@ babel / env放在此处,如下所示:

Then go to your package.json and add some scripts:

然后转到您的package.json并添加一些脚本:

We’ll have only one script that we’re gonna use in our project.

我们只有一个脚本要在我们的项目中使用。

“server” — It will mainly run our server.

“服务器” -主要运行我们的服务器。

服务器 (Server)

Now, in our root folder create the index.js file. It will be where we’re gonna make our server.

现在,在我们的根文件夹中创建index.js文件。 这将是我们要制造服务器的地方。

First, we’re gonna import all the modules that we’ll use.

首先,我们将导入所有将要使用的模块。

Then, we’re gonna create our connect with MongoDB using Mongoose:

然后,我们将使用Mongoose创建与MongoDB的连接:

What about that db const? This is where you’re gonna put your database URL to connect MongoDB. Then you’re gonna say to me: “But, I don’t have a database yet”, yes I got you. For that, we’re using MLab.

db const呢? 您将在这里放置数据库URL来连接MongoDB。 然后您要对我说:“但是,我还没有数据库”,是的,我知道了。 为此,我们正在使用MLab。

MLab is a database-as-a-service for MongoDB, all you need to do is go to their website (click here) and register.

MLab是MongoDB的数据库即服务,您所需要做的就是访问他们的网站( 单击此处 )并注册。

After you register, go and create a new database. To use as free, choose this option:

注册后,请创建一个新数据库。 要免费使用,请选择以下选项:

Choose US East (Virginia) as an option, and then give our database a name. After that, our database will show at the home page.

选择US East(Virginia)作为选项,然后为我们的数据库命名。 之后,我们的数据库将显示在主页上。

Click on our database, then go to User and create a new user. In this example, I’m gonna create a user called leo and password leoleo1.

单击我们的数据库,然后转到“ 用户”并创建一个新用户。 在此示例中,我将创建一个名为leo和密码leoleo1的用户

After our user is created, on the top of our page, we find two URLs. One to connect using Mongo Shell. The other to connect using a MongoDB URL. We copy the second one.

创建用户之后,在页面顶部,我们找到两个URL。 ØNE使用蒙戈壳牌连接 另一个使用MongoDB URL连接 我们复制第二个

After that, all you need to do is paste that URL on our db const at the index.js file. Our db const would look like this:

之后,您所需要做的就是将该URL粘贴到index.js文件的db const 我们的数据库常量看起来像这样:

表达 (Express)

Now we’re gonna finally start our server. For that, we’ve put some more lines in our index.js and we’re done.

现在我们终于要启动服务器了。 为此,我们在index.js中增加了几行,然后就完成了。

Now, run the command npm run server and go to localhost:4000/graphql and you’ll find a page like this:

现在,运行命令npm run server并转到localhost:4000 / graphql ,您将找到类似以下的页面:

MongoDB和架构 (MongoDB and Schema)

Now, in our root folder, make a folder named models and create a file inside called User.js (yes, with capital U).

现在,在我们的根文件夹中,创建一个名为models的文件夹,并在其中创建一个名为User.js的文件(是的,大写字母U)。

Inside of User.js, we’re gonna create our first schema in MongoDB using Mongoose.

在User.js内部,我们将使用Mongoose在MongoDB中创建第一个架构。

Now that we have created our User schema, we’re gonna start with GraphQL.

现在,我们已经创建了用户模式,我们将从GraphQL开始。

GraphQL (GraphQL)

In our root folder, we’re gonna create a folder called graphql. Inside that folder, we’re gonna create a file called index.js and two more folders: resolvers and types.

在我们的根文件夹中,我们将创建一个名为graphql的文件夹 在该文件夹内,我们将创建一个名为index.js的文件以及另外两个文件夹: resolverstypes

查询 (Queries)

Queries in GraphQL are the way we ask our server for data. We ask for the data that we need, and it returns exactly that data.

GraphQL中的查询是我们向服务器请求数据的方式。 我们要求我们需要的数据,并且它精确地返回该数据。

All our queries will be inside our types folder. Inside that folder, create an index.js file and a User folder.

我们所有的查询都将在我们的类型文件夹中。 在该文件夹内,创建一个index.js文件和一个User文件夹。

Inside the User folder, we’re gonna create an index.js file and write our queries.

在User文件夹内,我们将创建一个index.js文件并编写查询。

In our types folder, in our index.js file, we’re gonna import all the types that we have. For now, we have the User types.

在我们的types文件夹中的index.js文件中,我们将导入所有我们拥有的类型。 现在,我们有用户类型。

In case you have more than one type, you import that to your file and include in the typeDefs array.

如果您有多个类型, 则将其导入文件并包含在typeDefs数组中。

变异 (Mutations)

Mutations in GraphQL are the way we modify data in the server.

GraphQL中的突变是我们修改服务器中数据的方式。

All our mutations will be inside our resolvers folder. Inside that folder, create an index.js file and a User folder.

我们所有的变异都将在我们的resolvers文件夹中。 在该文件夹内,创建一个index.js文件和一个User文件夹。

Inside the User folder, we’re gonna create an index.js file and write our mutations.

在User文件夹中,我们将创建一个index.js文件并编写我们的变体。

Now that all our resolvers and mutations are ready, we’re gonna modularize our schema.

现在我们所有的解析器和变体都已准备就绪,我们将对我们的架构进行模块化。

模块化我们的架构 (Modularizing our schema)

Inside our folder called graphql, go to our index.js and make our schema, like this:

在名为graphql的文件夹中,转到我们的index.js并创建我们的架构,如下所示:

Now that our schema is done, go to our root folder and inside our index.js import our schema.

现在我们的模式已经完成,请转到我们的根文件夹,并在index.js内导入我们的模式。

After all that, our schema will end up like this:

毕竟,我们的模式将最终如下所示:

处理我们的查询和变异 (Playing with our queries and mutations)

To test our queries and mutations, we’re gonna start our server with the command npm run server, and go to localhost:4000/graphql.

为了测试我们的查询和变异,我们将使用命令npm run server启动服务器 ,并转到localhost:4000 / graphql。

创建用户 (Create user)

First, we’re gonna create our first user with a mutation:

首先,我们要创建第一个具有突变的用户:

mutation {  addUser(id: "1", name: "Dan Abramov", email: "dan@dan.com") {    id    name    email  }}

After that, if the GraphiQL playground returns to you the data object that we created, that means that our server is working fine.

之后,如果GraphiQL游乐场向您返回了我们创建的数据对象,则意味着我们的服务器运行正常。

To make sure, go to MLab, and inside of our users collection, check if there is our data that we just created.

为了确保安全,请转到MLab,然后在我们的用户集合中,检查是否有我们刚刚创建的数据。

After that, create another user called “Max Stoiber”. We add this user to make sure that our mutation is working fine and we have more than one user in the database.

之后,创建另一个用户“ Max Stoiber”。 我们添加此用户以确保我们的突变工作正常,并且数据库中有多个用户。

删除用户 (Delete user)

To delete a user, our mutation will go like this:

要删除用户,我们的变异将如下所示:

mutation {  deleteUser(id: "1", name: "Dan Abramov", email: "dan@dan.com") {    id    name    email  }}

Like the other one, if the GraphiQL playground returns to you the data object that we created, that means that our server is working fine.

像另一个一样,如果GraphiQL游乐场向您返回我们创建的数据对象,则意味着我们的服务器可以正常工作。

获取所有用户 (Get all users)

To get all users, we’re gonna run our first query like this:

为了获得所有用户,我们将像这样运行我们的第一个查询:

query {  users {    id    name    email  }}

Since we only have one user, it should return that exact user.

由于我们只有一个用户,因此应该返回该确切用户。

获取特定用户 (Get a specific user)

To get a specific user, this will be the query:

要获取特定用户,将是以下查询:

query {  user(id: "2"){    id    name    email  }}

That should return the exact user.

那应该返回确切的用户。

我们完成了! (And we’re done!)

Our server is running, our queries and mutations are working fine, we’re good to go and start our client. You can start with create-react-app. In your root folder just give the command create-react-app client and then, if you run the command npm run dev, our server and client will run concurrently!

我们的服务器正在运行,我们的查询和变体工作正常,我们很高兴开始启动客户端。 您可以从create-react-app开始。 在您的根文件夹中,输入命令create-react-app client ,然后,如果您运行命令npm run dev ,我们的服务器客户端将同时运行!

All the code from this article is available here.

本文提供了所有代码。

? Follow me on Twitter! Follow me on GitHub!

在Twitter上关注我! 在GitHub上关注我!

I’m looking for a remote opportunity, so if have any I’d love to hear about it, so please contact me!

我正在寻找机会,所以如果有任何我想听到的机会,请与我联系!

翻译自: https://www.freecodecamp.org/news/how-to-set-up-a-graphql-server-using-node-js-express-mongodb-52421b73f474/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值