json graphql_使用json-graphql-server模拟GraphQL API

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_使用json-graphql-server模拟GraphQL API_第1张图片

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”文件,如下所示:

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()方法来在浏览器中启动该模拟服务器。

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

你可能感兴趣的:(python,java)