json graphql

You may find that you need to set up a fast GraphQL server to test your frontend app’s behavior. Trying to do so, you quickly discover that creating even the simplest GraphQL server can be a very tedious task.

您可能会发现您需要设置一个快速的GraphQL服务器来测试前端应用程序的行为。 尝试这样做,您很快就会发现,即使是最简单的GraphQL服务器,也是一项非常繁琐的任务。

We need a simple way to serve JSON objects, very fast, without going through the hassle of actually setting up a real GraphQL server. To achieve that, we mock a GraphQL backend.

我们需要一种非常简单的方法来非常快速地提供JSON对象,而无需经历实际设置真正的GraphQL服务器的麻烦。 为此,我们模拟了GraphQL后端

Mocking is the practice of creating a fake version of a component, so that you can develop and test other parts of your application independently. Mocking your backend is a great way to quickly build a prototype of your frontend, and it lets you test your frontend without starting up any servers.

模拟是创建组件的伪版本的实践,以便您可以独立开发和测试应用程序的其他部分。 模拟后端是一种快速构建前端原型的好方法,它可以让您测试前端而无需启动任何服务器。

There are tons of ways to mock GraphQL backend in Nodejs but today we will use one of the easiest tools in the block, json-graphql-server.

有很多方法可以在Node.js中模拟GraphQL后端,但是今天我们将使用该块中最简单的工具之一json-graphql-server 。

What are going to learn here?

在这里要学什么?

We will learn:

我们将学习:

  • How to mock GraphQL APIs.如何模拟GraphQL API。
  • How to whip up a fake GraphQL backend using json-graphql-server.如何使用json-graphql-server鞭打伪造的GraphQL后端。

Tip: Use Bit (Github) to share, document, and manage reusable React components from different projects. It’s a great way to increase code reuse, speed up development, and build apps that scale.

提示 :使用Bit ( Github )共享,记录和管理来自不同项目的可重用React组件。 这是增加代码重用,加速开发并构建可扩展应用程序的好方法。

json-graphql-server (json-graphql-server)

json-graphql-server is a GraphQL backend mocking tool built by Marmelabs, inspired by the json-server utility. With json-graphql-server we can get a full fake GraphQL API with zero coding in less than 30 seconds.

json-graphql-server是Marmelabs建立的GraphQL后端模拟工具,灵感来自json-server实用程序。 使用json-graphql-server,我们可以在不到30秒的时间内获得具有零编码的完整伪造GraphQL API。

Using json-graphql-server is very simple and easy. First, it starts with installing the library as a global dependency:

使用json-graphql-server非常简单容易。 首先,首先将库安装为全局依赖项:

npm i json-graphql-server -g

With the above command, NPM will install json-graphql-server as a global utility in our machine which can then be used from anywhere in our machine.

使用上述命令,NPM将在我们的计算机中将json-graphql-server安装为全局实用程序,然后可以在我们的计算机中的任何位置使用它。

Next is defining your mock data in a js file. I’ll define my mock data in a db.js file. json-graphql-server says that the mock data from our js file must export an object with a list of entities. These entities should at least have an id key.

接下来是在js文件中定义您的模拟数据。 我将在db.js文件中定义模拟数据。 json-graphql-server说,我们js文件中的模拟数据必须导出带有实体列表的对象。 这些实体至少应具有一个id密钥。

// db.jsmodule.exports = {    users: [        {            id: 0,            name: "nnamdi",            age: 27        },        {            id: 1,            name: "chidume",            age: 29        },        {            id: 2,            name: "david",            age: 20        }    ]}

Here, we have a users array in our db.js file. Now, we start the json-graphql-server pointing it to our mock data in the db.file.

在这里,我们的db.js文件中有一个users数组。 现在,我们启动json-graphql-server,将其指向db.file中的模拟数据。

$ json-graphql-server db.js

json-graphql-server will start a GraphQL server at port 3000.

json-graphql-server将在端口3000上启动GraphQL服务器。

查询GraphQL服务器 (Querying the GraphQL server)

With our json-graphql-server server active, we can query for data.

在我们的json-graphql-server服务器处于活动状态时,我们可以查询数据。

Let’s see a simple users query:

让我们看一个简单的用户查询:

query {    User(id: 2) {        id        name        age    }}

We are querying for a user with “id” value of 2, and we are telling GraphQL that we want the “id”, “name”, and “age” properties to be included in the user. The result will be:

我们正在查询“ id”值为2的用户,并告诉GraphQL我们希望将“ id”,“ name”和“ age”属性包含在用户中。 结果将是:

{    "data": {        "user": {            "id": 0,            "name": "david",            "age": 20        }    }}

GraphQL enables you to state the type of data you want and how you want the data to look.

GraphQL使您能够声明所需数据的类型以及数据的外观。

This is a simple usage of json-graphql-server to mock a GraphQL backend, we just demonstrated that using a Users API.

这是json-graphql-server的简单用法,用于模拟GraphQL后端,我们只是演示了使用Users API。

We can go on to query for another User:

我们可以继续查询另一个用户:

query {    User(id: 0) {        id        name        age    }}

The above query will return:

上面的查询将返回:

{    "data": {        "user": {            "id": 0,            "name": "nnamdi",            "age": 27        }    }}

To get a list of all users, we perform the below query:

要获取所有用户的列表,我们执行以下查询:

query {    allUsers {        name        age    }}

This query will return all the users in the “users” array with the properties “name”, and “age” on each user:

此查询将返回“用户”数组中的所有用户,每个用户的属性为“名称”和“年龄”:

{    "data": {        "allUsers": [            {                name: "nnamdi",                age: 27            },            {                name: "chidume",                age: 29            },            {                name: "david",                age: 20            }        ]    }}

json-graphql-server enables us to paginate array results, filter them, sort results by fields, and even provide a condition for each entity in the returned array.

json-graphql-server使我们能够对数组结果进行分页,过滤,按字段对结果进行排序,甚至为返回数组中的每个实体提供条件。

更改端口号 (Changing the port number)

We can decide to start our mock json-graphql-server GraphQL server at another port if its default port 3000 is already taken by another server in your machine. json-graphql-server lets us do this by passing a --p flag to the json-graphql-sever in the terminal.

如果您计算机中的其他服务器已经使用了其默认端口3000,则可以决定在另一个端口上启动模拟json-graphql-server GraphQL服务器。 json-graphql-server通过在--p标志传递给json-graphql-sever ,使我们能够做到这一点。

$ json-graphql-server --p 4500

This will start a json-graphql-server GraphQL server at port 4500.

这将在端口4500上启动json-graphql-server GraphQL服务器。

Express.js的用法 (Usage with Express.js)

We have been using json-graphql-server from the CLI as a standalone utility. We can integrate json-graphl-server into an Express.js app.

我们一直在使用CLI中的json-graphql-server作为独立实用程序。 我们可以将json-graphl-server集成到Express.js应用程序中。

It is very easy to plug into an Express.js app:

插入Express.js应用非常容易:

...import jsonGraphqlExpress from 'json-graphql-server';...const port = 3000 || process.env.PORTconst data = {    users: [        {            id: 0,            name: "nnamdi",            age: 27        },        {            id: 1,            name: "chidume",            age: 29        },        {            id: 2,            name: "david",            age: 20        }    ]};app.use('/graphql', jsonGraphqlExpress(data));app.listen(port, () => {    console.log(`Server is listening on port ${port}`)});

Simple, we import jsonGraphqlExpress from json-graphql-server, then, setup up our mock JSON data. Finally, we call the jsonGraphqlExpress(data) with our mock data, it will return an Express.js middleware which we plug in the route "/graphql".

很简单,我们从json-graphql-server导入jsonGraphqlExpress ,然后设置我们的模拟JSON数据。 最后,我们用模拟data调用jsonGraphqlExpress(data) ,它将返回一个Express.js中间件,将其插入路由“ / graphql”。

We can now make query post to localhost:3000/graphql and GraphQL will serve us the mock data.

现在,我们可以将查询发布到localhost:3000/graphql并且GraphQL将为我们提供模拟数据。

http://localhost:3000/graphqlquery {    User(id: 0) {        id        name        age    }}{    "data": {        "user": {            "id": 0,            "name": "nnamdi",            "age": 27        }    }}

Note: The route must not be “/graphql” we can set it to anything, it will work provided we set jsonGraphqlExpress(data) as the middleware in the route.

注意 :路由不能为“ / graphql”,我们可以将其设置为任何值,只要将jsonGraphqlExpress(data)设置为路由的中间件,它就可以工作。

浏览器中的用法 (Usage in the browser)

json-graphql-server has support for usage in the browser. This is very useful when we are using XMLHttpRequest, or fetch or axios, or any other HTTP library from our browser.

json-graphql-server支持在浏览器中的使用。 当我们在浏览器中使用XMLHttpRequest,fetch或axios或任何其他HTTP库时,这非常有用。

Like always, it is very easy to set up between the browser script tags.

像往常一样,在浏览器脚本标记之间进行设置非常容易。

json-graphql-server bundles itself for use in browser, this exposes the JsonGraphqlServer as a global object so we reference the "json-graphql-server.min.js" file in the script tags like this:

json-graphql-server捆绑了自身以供在浏览器中使用,这JsonGraphqlServer公开为全局对象,因此我们在脚本标签中引用“ json-graphql-server.min.js”文件,如下所示:

<script src="./json-graphql-server.min.js"></script>

We can now call the JsonGraphqlServer passing in our url of choice and mock JSON data.JsonGraphqlServer returns an object which we use to start the mock server in our browser by calling its start() method.

现在,我们可以调用JsonGraphqlServer传递选择的URL和模拟JSON数据。 JsonGraphqlServer返回一个对象,我们通过调用该对象的start()方法来在浏览器中启动该模拟服务器。

<script type="text/javascript">    window.addEventListener('load', function() {        const data = [            {                id: 0,                name: "nnamdi",                age: 27            },            {                id: 1,                name: "chidume",                age: 29            },            {                id: 2,                name: "david",                age: 20            }        ];        const server = JsonGraphqlServer({            data,            url: 'http://localhost:3000/graphql'        });        server.start();</script>

Now, we can use XMLHttpRequest, axios, fetch, or any other HTTP library to query data.

现在,我们可以使用XMLHttpRequest,axios,fetch或任何其他HTTP库来查询数据。

XMLHttpRequest (XMLHttpRequest)

const xhr = new XMLHttpRequest();        xhr.open('POST', 'http://localhost:3000/graphql', true);        xhr.setRequestHeader('Content-Type', 'application/json');        xhr.setRequestHeader('Accept', 'application/json');        xhr.onerror = function(error) {            console.error(error);        }        xhr.onload = function() {            const result = JSON.parse(xhr.responseText);            console.log(result);        }        const body = JSON.stringify({ query: 'query allUsers { name age }' });        xhr.send(body);    });

取 (Fetch)

fetch({    url: 'http://localhost:3000/graphql',    method: 'POST',    body: JSON.stringify({ query: 'query allUsers { name age }' })}).then(response => response.json()).then(json => {    console.log(result);})

Axios (Axios)

axios({    url: 'http://localhost:3000/graphql',    method: 'POST',    data: JSON.stringify({ query: 'query allUsers { name age }' })}).then(res => {    console.log(res);})

翻译自: https://blog.bitsrc.io/mock-graphql-apis-using-json-graphql-server-c1c6e5f7793

json graphql


http://www.taodudu.cc/news/show-6999474.html

相关文章:

  • shiro解决cors_使用Netlify Dev彻底解决CORS
  • metaRTC6.0 janus推流操作指南
  • java 开源 server_simplewebserver: SimpleWebServer 是一款使用Java基于NIO编写的超轻量级开源Web Application Server...
  • 使用sql服务器发送贺卡_使用Microsoft Word做最后一分钟的节日贺卡
  • WHIP WHEP:WebRTC 是直播的未来吗?
  • 什么叫同时处理两个ajax请求?
  • WHIP 和 WHEP 协议简介
  • 流媒体协议分析之webrtc 协议 srs 服务器实现
  • 让office2007右键新建97-03版本的doc,xls.ppt文件
  • office2007新建word文档,打开后跳出转换文件对话框的解决方法
  • Office2007与Microsoft Office SharePoint2007的配置和注意事项!
  • Windows 7安装以及VS2008和Office2007冲突的问题
  • office2007,每次打开之前都要配置更新,解决办法
  • Office2007和PowerDesigner12.5冲突,Word2007中鼠标不能使用
  • office2003和office2007共享(doc用03打开,docx用07打开)
  • 解决office2003与office2007共存问题
  • 解决Office 2007每次打开都要出现 配置Microsoft Office Professional Plus 2007
  • VC Office2007界面对话框实现(续)
  • 安装Office2007后,每次启动的时候都要显示配置进度解决
  • 如何利用 ArcGIS Pro 和 Landsat 8 图像计算叶绿素指数和全球环境监测指数
  • 全球幸福指数调查 中国居31发达国家排名靠后
  • [双语阅读]全球幸福指数大调查 富国反而不快乐
  • 基于Python的世界各个国家的幸福度的公开数据集的数据挖掘
  • 全球开发者幸福指数报告新发现
  • 和计算机专业学生谈学英语
  • 1000句最常用英语口语 ------考研论坛 bbs.kaoyan.com
  • 用vim还是用vs呢
  • 【转】无所不能的vim-vim到底能做什么
  • vis.js 小记
  • 手把手教你使用vue创建第一个vis.js

json graphql_使用json-graphql-server模拟GraphQL API相关推荐

  1. java通用象棋游戏_在通用国际象棋界面周围模拟GraphQL包装器

    java通用象棋游戏 The Universal Chess Interface (UCI) has been around a long time and used by many chess en ...

  2. 为什么说 GraphQL 可以取代 REST API?

    几年前,我在 DocuSign 带领了一个开发团队,任务是重写一个有数千万个用户在使用的 Web 应用程序.当时还没有可以支持前端的 API,因为从一开始,Web 应用程序就是一个.NET 大单体.西 ...

  3. 为什么说GraphQL可以取代REST API?

    几年前,我在DocuSign带领了一个开发团队,任务是重写一个有数千万个用户在使用的Web应用程序.当时还没有可以支持前端的API,因为从一开始,Web应用程序就是一个.NET大单体.西雅图的API团 ...

  4. python中json.dumps和json.loads,get和post

    一.json.dumps()和json.loads()概念理解 1.json.dumps()和json.loads()是json格式处理函数(可以这么理解,json是字符串) json.dumps() ...

  5. JSON数据 与 JSON数据的使用

    一.JSON数据 JSON:JavaScript 对象表示法(JavaScript Object Notation).根据这个定义,需要稍微了解JavaScript对象的格式 var obj={ &q ...

  6. JSON解析:JSON对象还能这样???

    自信平生无愧事,死后方敢对青天. 有目录,不迷路 前言 缘由 转换 蹊径 前言 愉快的(3+7=8的)中秋国庆假期已经接近尾声,特此写篇博客聊以记录学习过程尽早进入学习状态,也便不陷入假期综合征,使得 ...

  7. js form表单转json字符串,json数组转json字符串出现多余的双引号问题解决

    功能介绍         页面展示的是一个用户的基本信息,和该用户对应的几台车辆的信息,车辆的字段属性都一样.然后可以编辑这些信息,再保存到后台.那么就需要考虑将车辆信息转换为json数组类型的字符串 ...

  8. asp ajax返回json数据类型,asp怎么返回json asp返回json是否通信成功等参数

    相信大家对于asp和json都不陌生,当下json应用的非常广泛,但asp语言中并没有可以直接生成json对象的方法,这个就比较麻烦了.还好现在有了JSON.asp和json.js 了 下面介绍 as ...

  9. cjson构建_[置顶] cJSON库(构建json与解析json字符串)-c语言

    一.c语言获取json中的数据. 1.先要有cJOSN库,两个文件分别是cJSON.c和cJSON.h. 2.感性认识 char * json = "{ \"json\" ...

最新文章

  1. MongoDB(一):简介
  2. unity中单位是米还是厘米_小学数学常用单位换算汇总,收藏起来方便孩子查阅...
  3. Music Problem
  4. maven 打包编译_您是否真的想加快Maven的编译/打包速度? 那么takari生命周期插件就是答案。...
  5. oracle导数的数据乱码,Oracle10g导数据时中文乱码相关处理
  6. 唐宇迪数据分析学习笔记
  7. 数值方法与计算机方法是,计算机数值方法.pdf
  8. TP5 ZipArchive 的坑
  9. 开源究竟差哪了--- 关于开源软件和自由软件的区别
  10. GUI-Guider中文手册
  11. qt开源项目: tiled 瓦片 游戏地图编辑器
  12. 在进化计算中,软件进行元基编码的新陈代谢方式 V0. 1. 0
  13. 越狱Season 1-Episode 1: the pilot
  14. 2017年营销行业八大趋势预测,H5居然...
  15. c++ opencv 身份证OCR识别:前期数据训练库准备(tesseractOCR)
  16. 思科access-list 1 permit 1.1.1.0 0.0.254.0 //允许第三位为奇数的路由
  17. 关于 The document “(null)” requires Xcode 8.0 or later. 解决方法
  18. OneNote for Windows 10 快捷键大全
  19. [编程] Java8 Stream(流式计算) 常见的一些用法汇总
  20. 阿里云oss对象存储跨域设置

热门文章

  1. 进制的转换(二进制,十进制,八进制,十六进制)
  2. 货拉拉NLP算法实习生面试
  3. WLAN 中 AC与AP的关系
  4. 互联网时代即时通讯软件的利与弊
  5. navicat 连接mysql报错10055问题
  6. java下载word,解决文件名中文乱码的问题(包括edge跟ie11)
  7. 新的挑战:期待、恐惧
  8. 密码认证-SHA加盐密码
  9. 日系服装搭配出甜美与性感
  10. Linux学习:Linux的发展历史及特点