如何使用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/

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/393086.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/393086.shtml
英文地址,請注明出處:http://en.pswp.cn/news/393086.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

leetcode954. 二倍數對數組(treemap)

給定一個長度為偶數的整數數組 A&#xff0c;只有對 A 進行重組后可以滿足 “對于每個 0 < i < len(A) / 2&#xff0c;都有 A[2 * i 1] 2 * A[2 * i]” 時&#xff0c;返回 true&#xff1b;否則&#xff0c;返回 false。 示例 1&#xff1a; 輸入&#xff1a;[3,1,…

linux文件內容打印成二進制,如何在二進制文件中只打印可打印字符(相當于Linux下的字符串)?...

在Python3中&#xff0c;以二進制模式打開文件會得到bytes的結果。迭代一個bytes對象可以得到0到255(包括0到255)的整數&#xff0c;而不是字符。從^{} documentation&#xff1a;While bytes literals and representations are based on ASCII text, bytes objects actually b…

1098 均分紙牌

1098 均分紙牌 2002年NOIP全國聯賽提高組 時間限制: 1 s 空間限制: 128000 KB 題目等級 : 黃金 Gold 題目描述 Description有 N 堆紙牌&#xff0c;編號分別為 1&#xff0c;2&#xff0c;…, N。每堆上有若干張&#xff0c;但紙牌總數必為 N 的倍數。可以在任一堆上取若于張紙…

輕松學習分布式|系列3|分布式數據庫。

我們繼續來講分布式&#xff0c;回到我們的創業游戲。 我們的業務規模上來了&#xff0c;客戶也越來越忠誠了。很多客戶都通過我們的訂票服務&#xff0c;來方便自己的行程。 那對這些老客戶&#xff0c;我們的宗旨是&#xff1a;要不斷超越客戶的期待。 所以&#xff0c;我們要…

量子運算 簡單通俗例子_什么是量子計算機? 用一個簡單的例子解釋。

量子運算 簡單通俗例子by YK Sugi由YK Sugi 什么是量子計算機&#xff1f; 用一個簡單的例子解釋。 (What is a quantum computer? Explained with a simple example.) Hi everyone!嗨&#xff0c;大家好&#xff01; The other day, I visited D-Wave Systems in Vancouver…

linux增加端口失敗,端口沒被占用,怎么會bind失敗呢?

今天在一個服務器上部署一個webserver的時候&#xff0c;提示我bind端口失敗&#xff0c;我習慣性的用netstat看了下&#xff0c;沒有被占用啊&#xff01;把問題分享出來后&#xff0c;給力的同事們搜索到了ip_local_port_range這個東西這個東西對應的是/proc/sys/net/ipv4/ip…

leetcode面試題 17.15. 最長單詞

給定一組單詞words&#xff0c;編寫一個程序&#xff0c;找出其中的最長單詞&#xff0c;且該單詞由這組單詞中的其他單詞組合而成。若有多個長度相同的結果&#xff0c;返回其中字典序最小的一項&#xff0c;若沒有符合要求的單詞則返回空字符串。 示例&#xff1a; 輸入&am…

Restful API 設計

1. 簡介 目前 "互聯網軟件"從用客戶端/服務端模式&#xff0c;建立在分布式體系上&#xff0c;通過互聯網通訊&#xff0c;具有高延時、高開發等特點。但是軟件開發和網絡是兩個不同的領域&#xff0c;交集很少。要使得兩個融合&#xff0c;就要考慮如何在互聯網環境…

sql行數少于10_如何用少于100行的代碼創建生成藝術

sql行數少于10by Eric Davidson埃里克戴維森(Eric Davidson) 如何用少于100行的代碼創建生成藝術 (How to Create Generative Art In Less Than 100 Lines Of Code) Generative art, like any programming topic, can be intimidating if you’ve never tried it before. I’v…

安裝輸入發

直接在系統 ——系統管理 ——語言支持 選——中文從新啟動 sudo apt-get install scim-pinyin安裝JAVA環境支持 sudo apt-get install sun-java-jre()要是 apt -get 命令不能用 可能是你 的 源有問題 可以 更新一下 在系統 &#xff0d;系統管理 源設置 選這臺灣的 就可以 …

(第2篇)一篇文章教你輕松安裝hadoop

摘要: 這篇文章將會手把手教你安裝hadoop&#xff0c;只要你細心按照文章中的步驟操作&#xff0c;hadoop肯定能正確安裝&#xff0c;絕對不會讓你崩潰 博主福利 給大家贈送一套hadoop視頻課程 授課老師是百度 hadoop 核心架構師 內容包括hadoop入門、hadoop生態架構以及大型ha…

linux cpio到指定目錄,linux cpio命令存取歸檔包中的文件

功能描述使用cpio命令可以通過重定向的方式將文件進行打包備份及還原恢復&#xff0c;它可以解壓縮以“.cpio”或者“.tar”結尾的文件。命令語 法cpio [選項] [目標目錄]選項含義選項含義-o執行 copy-out 模式&#xff0c;建立備份檔。-i執行 copy-in 模式&#xff0c;還原備份…

leetcode劍指 Offer 20. 表示數值的字符串

請實現一個函數用來判斷字符串是否表示數值&#xff08;包括整數和小數&#xff09;。例如&#xff0c;字符串"100"、“5e2”、"-123"、“3.1416”、"-1E-16"、“0123"都表示數值&#xff0c;但"12e”、“1a3.14”、“1.2.3”、"…

python接口自動化2-發送post請求

前言 發送post的請求參考例子很簡單&#xff0c;實際遇到的情況卻是很復雜的&#xff0c;首先第一個post請求肯定是登錄了&#xff0c;但登錄是最難處理的。登錄問題解決了&#xff0c;后面都簡單了。 一、查看官方文檔 1.學習一個新的模塊&#xff0c;其實不用去百度什么的&am…

簡介瀏覽器內核與JavaScript引擎

本文介紹了常用瀏覽器內核與JavaScript引擎 一、瀏覽器內核 Rending Engine, 顧名思義&#xff0c;稱之為渲染網頁內容的&#xff0c;將網頁的代碼轉換為你看得見的頁面&#xff0c;因為是排版&#xff0c;所以排版&#xff0c;所以肯定會有排版錯誤等問題。為什么會有排版錯誤…

Linux查看tar實用程序,linux tar指令常用選項

linux的tar指令經常被用到&#xff0c;因為壓縮文件的時候通常需要打包文檔&#xff0c;而tar指令就是打包指令&#xff0c;同時gzip壓縮程序和bzip2壓縮程序都是支持tar指令的&#xff0c;所以tar指令在打包的同時還可以用gzip和bzip進行壓縮&#xff0c;這樣多文件可以打包的…

代碼字體mono_如何構建代碼存儲庫:Multi,Mono或Organic?

代碼字體monoby Chetan Sharma由Chetan Sharma 如何構建代碼存儲庫&#xff1a;Multi&#xff0c;Mono或Organic&#xff1f; (How to Structure Code Repositories: Multi, Mono, or Organic?) The newest debate in town is whether you should keep your services in a si…

leetcode1424. 對角線遍歷 II(排序)

給你一個列表 nums &#xff0c;里面每一個元素都是一個整數列表。請你依照下面各圖的規則&#xff0c;按順序返回 nums 中對角線上的整數。 示例 1&#xff1a; 輸入&#xff1a;nums [[1,2,3],[4,5,6],[7,8,9]] 輸出&#xff1a;[1,4,2,7,5,3,8,6,9] 代碼 class Solution …

DaVinci各版本安裝指南

鏈接: https://pan.baidu.com/s/1g1kaXZxcw-etsJENiW2IUQ?pwd0531 ? #2024版 1.鼠標右擊【DaVinci_Resolve_Studio_18.5(64bit)】壓縮包&#xff08;win11及以上系統需先點擊“顯示更多選項”&#xff09;【解壓到 DaVinci_Resolve_Studio_18.5(64bit)】。 2.打開解壓后的文…

使用 Servlet 讀取表單數據

Technorati 標簽: servlet&#xff1b;java 一、概述 Servlet 有一個比較好的功能就是可以自動處理表單提交的數據。我們只需要調用HttpServletRequest#getParameter(String name),就可以獲得指定參數的值&#xff08;String&#xff09;&#xff0c;注意此方法是大小寫敏感的。…