?如何在2分鐘內將GraphQL服務器添加到RESTful Express.js API

You can get a lot done in 2 minutes, like microwaving popcorn, sending a text message, eating a cupcake, and hooking up a GraphQL server.

您可以在2分鐘內完成很多工作,例如微波爐爆米花,發送短信, 吃蛋糕以及連接GraphQL服務器

Yup. If you have an old Express.js RESTful API lying around or you're interested in incrementally adopting GraphQL, we only need 2 minutes to hook it up with a fresh new GraphQL Server.

對。 如果您有一個舊的Express.js RESTful API,或者對逐步采用GraphQL感興趣,我們只需2分鐘即可將其與新的GraphQL Server連接起來。

Ready? Set. Go!

準備? 組。 走!

Let's say that your server looked something like the following.

假設您的服務器如下所示。

import express from 'express';
import { apiRouter } from './router';const app = express();
const port = process.env.PORT || 5000;// Existing routes for our Express.js app
app.use('/api/v1', apiRouter);app.listen(port, () => console.log(`[App]: Listening on port ${port}`))

At the root of your project, npm install apollo-server-express as a dependency.

在項目的根目錄下, npm install apollo-server-express npm install為依賴項。

npm install apollo-server-express --save

Go to where your Express app is defined and import ApolloServer and gql from apollo-server-express.

轉到定義Express應用程序的位置,然后從apollo-server-express導入ApolloServergql

import { ApolloServer, gql } from 'apollo-server-express'

Next, create an instance of an ApolloServer with the simplest possible GraphQL type definitions and resolvers.

接下來,使用最簡單的 GraphQL 類型定義解析器創建ApolloServer的實例。

const server = new ApolloServer({typeDefs: gql`type Query {hello: String}`,resolvers: {Query: {hello: () => 'Hello world!',},}
})

Lastly, use ApolloServer's applyMiddleware method to pass in our Express.js server.

最后,使用ApolloServer的applyMiddleware方法傳遞我們的Express.js服務器。

server.applyMiddleware({ app })

Boom. That's it!

繁榮。 而已!

Your code should look something like this.

您的代碼應如下所示。

import express from 'express';
import { v1Router } from './api/v1';
import { ApolloServer, gql } from 'apollo-server-express'const app = express();
const port = process.env.PORT || 5000;const server = new ApolloServer({typeDefs: gql`type Query {hello: String}`,resolvers: {Query: {hello: () => 'Hello world!',},}
})server.applyMiddleware({ app })app.use('/api/v1', v1Router);app.listen(port, () => {console.log(`[App]: Listening on port ${port}`)
})

If you navigate to localhost:5000/graphql, you should be able to see your GraphQL schema in the GraphQL playground.

如果導航到localhost:5000/graphql ,則應該能夠在GraphQL游樂場中看到GraphQL模式。

Note: If you want to change the URL that the GraphQL endpoint sits at from /graphql to something else, you can pass in a path option to server.applyMiddleware() with the URL you want, like path: '/specialUrl'. Check out the docs for full API usage.

注意:如果要將GraphQL端點所在的URL從/graphql為其他名稱,則可以將path選項與所需URL傳遞給server.applyMiddleware() ,例如path: '/specialUrl' 。 查看文檔以了解完整的API使用情況。

How simple was that? Is your popcorn finished? 😉

那有多簡單? 爆米花吃完了嗎? 😉

摘要 (Summary)

Here's what we did.

這就是我們所做的。

  1. Install apollo-server-express

    安裝apollo-server-express

  2. Create a new ApolloServer

    創建一個new ApolloServer

  3. Connect your GraphQL Server with server.applyMiddleware

    將GraphQL Server與server.applyMiddleware連接

I personally really love the fact that Apollo Server is non-intrusive and can be tacked on any project as an alternative way to communicate between services and applications.

我個人真的很喜歡Apollo Server是非侵入性的,并且可以作為任何在服務和應用程序之間進行通信的替代方式而適用于任何項目。

從這往哪兒走 (Where to go from here)

If you're new to Apollo and GraphQL, a great way to learn is to actually build something in real life. For that reason, I highly recommend checking out the Apollo Fullstack Tutorial (you can also learn in TypeScript now 🔥).

如果您是Apollo和GraphQL的新手,那么學習的一種好方法是在現實生活中實際構建一些東西。 因此,我強烈建議您查看Apollo Fullstack教程(您現在也可以在TypeScript中學習🔥) 。

I'm Khalil Stemmler, a Developer Advocate at Apollo GraphQL. I teach advanced TypeScript, GraphQL, and Node.js best practices for large-scale applications. Feel free to ping me on Twitter if you need help with anything Apollo, TypeScript, or architecture-related. Cheers 🤠

我是Apollo GraphQL的開發人員倡導者Khalil Stemmler 。 我為大型應用程序教授高級TypeScript,GraphQL和Node.js最佳實踐。 如果您需要有關Apollo,TypeScript或與體系結構相關的任何幫助,請隨時在Twitter上對我進行ping操作。 干杯🤠

翻譯自: https://www.freecodecamp.org/news/add-a-graphql-server-to-a-restful-express-js-api-in-2-minutes/

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

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

相關文章

leetcode 1744. 你能在你最喜歡的那天吃到你最喜歡的糖果嗎?

給你一個下標從 0 開始的正整數數組 candiesCount ,其中 candiesCount[i] 表示你擁有的第 i 類糖果的數目。同時給你一個二維數組 queries ,其中 queries[i] [favoriteTypei, favoriteDayi, dailyCapi] 。 你按照如下規則進行一場游戲: 你…

回歸分析_回歸

回歸分析Machine learning algorithms are not your regular algorithms that we may be used to because they are often described by a combination of some complex statistics and mathematics. Since it is very important to understand the background of any algorith…

ruby nil_Ruby中的數據類型-True,False和Nil用示例解釋

ruby niltrue, false, and nil are special built-in data types in Ruby. Each of these keywords evaluates to an object that is the sole instance of its respective class.true , false和nil是Ruby中的特殊內置數據類型。 這些關鍵字中的每一個都求值為一個對…

淺嘗flutter中的動畫(淡入淡出)

在移動端開發中,經常會有一些動畫交互,比如淡入淡出,效果如圖: 因為官方封裝好了AnimatedOpacity Widget,開箱即用,所以我們用起來很方便,代碼量很少,做少量配置即可,所以&#xff0…

數據科學還是計算機科學_何時不使用數據科學

數據科學還是計算機科學意見 (Opinion) 目錄 (Table of Contents) Introduction 介紹 Examples 例子 When You Should Use Data Science 什么時候應該使用數據科學 Summary 摘要 介紹 (Introduction) Both Data Science and Machine Learning are useful fields that apply sev…

空間復雜度 用什么符號表示_什么是大O符號解釋:時空復雜性

空間復雜度 用什么符號表示Do you really understand Big O? If so, then this will refresh your understanding before an interview. If not, don’t worry — come and join us for some endeavors in computer science.您真的了解Big O嗎? 如果是這樣&#xf…

leetcode 523. 連續的子數組和

給你一個整數數組 nums 和一個整數 k ,編寫一個函數來判斷該數組是否含有同時滿足下述條件的連續子數組: 子數組大小 至少為 2 ,且 子數組元素總和為 k 的倍數。 如果存在,返回 true ;否則,返回 false 。 …

Docker學習筆記 - Docker Compose

一、概念 Docker Compose 用于定義運行使用多個容器的應用,可以一條命令啟動應用(多個容器)。 使用Docker Compose 的步驟: 定義容器 Dockerfile定義應用的各個服務 docker-compose.yml啟動應用 docker-compose up二、安裝 Note t…

創建shell腳本

1.寫一個腳本 a) 用touch命令創建一個文件:touch my_script b) 用vim編輯器打開my_script文件:vi my_script c) 用vim編輯器編輯my_script文件,內容如下: #!/bin/bash 告訴shell使用什么程序解釋腳本 #My first script l…

線性回歸算法數學原理_線性回歸算法-非數學家的高級數學

線性回歸算法數學原理內部AI (Inside AI) Linear regression is one of the most popular algorithms used in different fields well before the advent of computers. Today with the powerful computers, we can solve multi-dimensional linear regression which was not p…

您應該在2020年首先學習哪種編程語言? ????d???s????:???su?

Most people’s journey toward learning to program starts with a single late-night Google search.大多數人學習編程的旅程都是從一個深夜Google搜索開始的。 Usually it’s something like “Learn ______”通常它類似于“學習______” But how do they decide which la…

Linux 概述

UNIX發展歷程 第一個版本是1969年由Ken Thompson(UNIX之父)在AT& T貝爾實驗室實現Ken Thompson和Dennis Ritchie(C語言之父)使用C語言對整個系統進行了再加工和編寫UNIX的源代碼屬于SCO公司(AT&T ->Novell …

課程一(Neural Networks and Deep Learning),第四周(Deep Neural Networks)—— 0.學習目標...

Understand the key computations underlying deep learning, use them to build and train deep neural networks, and apply it to computer vision. 學習目標 See deep neural networks as successive blocks put one after each otherBuild and train a deep L-layer Neura…

使用ActionTrail Python SDK

ActionTrail提供官方的Python SDK。本文將簡單介紹一下如何使用ActionTrail的Python SDK。 安裝Aliyun Core SDK。 pip install aliyun-python-sdk-core 安裝ActionTrail Python SDK。 pip install aliyun-python-sdk-actiontrail 下面是測試的代碼。調用LookupEventsRequest獲…

泰坦尼克:機器從災難中學習_用于災難響應的機器學習研究:什么才是好的論文?...

泰坦尼克:機器從災難中學習For the first time in 2021, a major Machine Learning conference will have a track devoted to disaster response. The 16th Conference of the European Chapter of the Association for Computational Linguistics (EACL 2021) has a track on…

github持續集成的設置_如何使用GitHub Actions和Puppeteer建立持續集成管道

github持續集成的設置Lately Ive added continuous integration to my blog using Puppeteer for end to end testing. My main goal was to allow automatic dependency updates using Dependabot. In this guide Ill show you how to create such a pipeline yourself. 最近&…

shell與常用命令

虛擬控制臺 一臺計算機的輸入輸出設備就是一個物理的控制臺 ; 如果在一臺計算機上用軟件的方法實現了多個互不干擾獨立工作的控制臺界面,就是實現了多個虛擬控制臺; Linux終端的工作方式是字符命令行方式,用戶通過鍵盤輸入命令進…

C中的malloc:C中的動態內存分配

什么是C中的malloc()? (What is malloc() in C?) malloc() is a library function that allows C to allocate memory dynamically from the heap. The heap is an area of memory where something is stored.malloc()是一個庫函數,它允許C從堆動態分配…

Linux文本編輯器

Linux文本編輯器 Linux系統下有很多文本編輯器。 按編輯區域: 行編輯器 ed 全屏編輯器 vi 按運行環境: 命令行控制臺編輯器 vi X Window圖形界面編輯器 gedit ed 它是一個很古老的行編輯器,vi這些編輯器都是ed演化而來。 每次只能對一…

Alpha第十天

Alpha第十天 聽說 031502543 周龍榮(隊長) 031502615 李家鵬 031502632 伍晨薇 031502637 張檉 031502639 鄭秦 1.前言 任務分配是VV、ZQ、ZC負責前端開發,由JP和LL負責建庫和服務器。界面開發的教輔材料是《第一行代碼》,利用And…