博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
vue中的突变方法在哪_GraphQL中的突变和订阅
阅读量:2504 次
发布时间:2019-05-11

本文共 8722 字,大约阅读时间需要 29 分钟。

vue中的突变方法在哪

In this article we’ll be looking at using the Mutation and Subscription types to manipulate and watch our data for changes, instead of just querying, in GraphQL. Feel free to discover more in the .

在本文中,我们将研究在GraphQL中使用MutationSubscription类型来操纵和观察数据的变化,而不仅仅是查询。 随时在发现更多内容。

To keep things simple, we won’t be using any databases or HTTP requests, but knowing how to set up a basic API with is necessary.

为简单起见,我们不会使用任何数据库或HTTP请求,但是必须知道如何使用设置基本API。

安装 (Installation)

We’ll be using the library to setup our server and nodemon to have it reload automatically. We’ll also need a pre-prossesor like or so we can use JavaScript’s latest features.

我们将使用库来设置服务器和nodemon以使其自动重新加载。 我们还需要像或这样的pre-prosoror,以便我们可以使用JavaScript的最新功能。

$ npm i graphql-yoga nodemon

样板设置 (Boilerplate Setup)

Besides our server setup we just have an empty users array and a simple schema and resolver for returning all our users.

除了我们的服务器设置外,我们只有一个空的users数组以及一个用于返回所有用户的简单架构和解析器。

server.js
server.js
import { GraphQLServer } from 'graphql-yoga'const users = [];const typeDefs = `  type Query {    users: [User!]!  }  type User {    name: String!    age: Int!  }`;const resolvers = {  Query: {    user() {      return users;    }  }}const server = new GraphQLServer({ typeDefs, resolvers });server.start(() => console.log('server running'));

We’ll need a start script that’ll run nodemon on our output file:

我们需要一个start脚本,该脚本将在输出文件上运行nodemon:

package.json
package.json
{  "name": "graphql-api",  "version": "1.0.0",  "description": "",  "main": "server.js",  "dependencies": {    "graphql-yoga": "^1.16.7"  },  "devDependencies": {    "nodemon": "^1.19.1"  },  "scripts": {    "start": "nodemon server-dist.js"  },  "author": "",  "license": "ISC"}

Now in the terminal you can just run npm run start.

现在,您可以在终端中运行npm run start

Over at localhost:4000 we should have up and running with a query for user { name } returning our empty array.

localhost:4000我们应该并运行对user { name }的查询, user { name }返回我们的空数组。

创建变异 (Create Mutation)

The syntax for our mutations is almost the same as for our query. We just need to declare what options we want, add any arguments (if any), and declare what type should be returned when completed.

我们的变异语法与我们的查询几乎相同。 我们只需要声明所需的选项,添加任何参数(如果有),并声明完成后应返回的类型。

Instead of adding all of out arguments inline, it’s pretty common to break the data into its own special type called an input type for the sake of organization. It’s a general naming convention you’ll see in tools like to name the input whatever the resolver is ending with the word input, so addUser gets an AddUserInput input.

不用内联添加所有out参数,为组织起见,将数据分成自己的特殊类型(称为input类型)是很常见的。 您会在工具中看到这是一个通用的命名约定,无论解析程序以单词input结束时, addUser都会为输入addUser ,因此addUser获得AddUserInput输入。

server.js
server.js
const typeDefs = `  type Mutation {    addUser(data: AddUserInput): User!  }  input AddUserInput {    name: String!,     age: Int!  }`;

Just like with queries, we can access the arguments on args and add our new user to our array, and return them.

就像查询一样,我们可以访问args上的args ,并将新用户添加到数组中,然后返回它们。

const resolvers = {  Query: {...},  Mutation: {    addUser(parent, args, ctx, info) {      const user = { ...args.data };      users.push(user);      return user;    }  }}

删除和更新变异 (Delete and Update Mutations)

With the syntax being so simple, it’s almost effortless to flesh out the other CRUD operations.

语法非常简单,充实其他CRUD操作几乎毫不费力。

We’ll know which item we’re removing or updating by just searching for the user by name.

通过按名称搜索用户,我们将知道要删除或更新的项目。

server.js
server.js
const typeDefs = `  type Mutation {    deleteUser(name: String!): User!    updateUser(name: String!, data: UpdateUserInput): User!  }  input UpdateUserInput {    name: String    age: Int  }`const resolvers = {  Query: { ... },  Mutation: {    deleteUser(parent, args, ctx, info) {      // We're just finding the index of the user with a matching name,      // checking if it exists, and removing that section of the array.      const userIndex = users.findIndex(user => user.name.toLowerCase() === args.name.toLowerCase());      if (userIndex === -1) throw new Error('User not found');      const user = users.splice(userIndex, 1);      return user[0];    },    updateUser(parent, args, ctx, info) {      const user = users.find(user => user.name.toLowerCase() === args.who.toLowerCase());      if (!user) throw new Error('User not found');      // This way, only the fields that are passed-in will be changed.      if (typeof args.data.name === "string") user.name = args.data.name;      if (typeof args.data.age !== "undefined") user.age = args.data.age;      return user;    }  }}

Now over at localhost:4000 you can try this mutation and query for our array again.

现在在localhost:4000结束,您可以尝试这种突变并再次查询我们的数组。

mutation {  addUser(data: {    name: "Alli",    age: 48  }) {    name    age  }}

Or in another tab:

或在另一个标签中:

mutation {  updateUser(name: "Alli", data: {    name: "Crusher",    age: 27  }) {    name    age  }}

订阅内容 (Subscriptions)

We can use the special Subscription type to let us watch for any changes to our data. The syntax is very similar to that of queries and mutations, just add the type Subscription, add whatever you want it to watch, and what you want returned. We’re going to return a custom type that will send us back both our changed data and tell us whether it was a create, delete, or update operation.

我们可以使用特殊的Subscription类型来监视数据的任何更改。 语法与查询和变异的语法非常相似,只需添加Subscription类型,添加您想要观看的内容以及返回的内容。 我们将返回一个自定义类型,该类型将向我们发送更改后的数据,并告诉我们它是创建,删除还是更新操作。

To use subscriptions we’re going to need to use PubSub from graphql-yoga and initialize it before everything else. Over in our subscription resolver we’ll use a function called subscribe which will need to return an asynchronous event, which we’ll name user. Whenever we want to connect something to this subscription we will use this event name.

要使用订阅我们将需要使用PubSub从graphql瑜伽和其他一切之前对其进行初始化。 在我们的订阅解析器,我们将使用一个名为函数subscribe ,这将需要返回异步事件,我们将其命名为user 。 每当我们想要将某些内容连接到此订阅时,我们都将使用此事件名称。

server.js
server.js
import { GraphQLServer, PubSub } from 'graphql-yoga';const pubsub = new PubSub();const typeDefs = `type Subscription {  user: UserSubscription!}type UserSubscription {  mutation: String!  data: User!}`const resolvers = {  Query: { ... },  Mutation: { ... },  Subscription: {    user: {      subscribe() {        return pubsub.asyncIterator('user');      }    }}}

Our subscription itself is setup and available in the generated GraphQL docs, but it doesn’t know when to fire or what to return. Back in our mutations, we’ll add pubsub.publish to link to our user event and pass our data back.

我们的订阅本身已设置,并且在生成的GraphQL文档中可用,但它不知道何时触发或返回什么。 回到我们的变异中,我们将添加pubsub.publish链接到我们的user事件,并将数据传回。

const resolvers = {  Query: { ... },  Mutation: {    addUser(parent, args, ctx, info) {      const user = { ...args.data };      users.push(user);      // We'll just link it to our user event,      // and return what type of mutation this is and our new user.      pubsub.publish("user", {        user: {          mutation: "Added",          data: user        }      });      return user;    },    deleteUser(parent, args, ctx, info) {      const userIndex = users.findIndex(        user => user.name.toLowerCase() === args.who.toLowerCase()      );      if (userIndex === -1) throw new Error("User not found");      const user = users.splice(userIndex, 1);      pubsub.publish("user", {        user: {          mutation: "Deleted",          data: user[0]        }      });      return user[0];    },    updateUser(parent, args, ctx, info) {      const user = users.find(        user => user.name.toLowerCase() === args.who.toLowerCase()      );      if (!user) throw new Error("User not found");      if (typeof args.data.name === "string") user.name = args.data.name;      if (typeof args.data.age !== "undefined") user.age = args.data.age;      pubsub.publish("user", {        user: {          mutation: "Updated",          data: user        }      });      return user;    }  },  Subscription: { ... }};

Over at localhost:4000 we can open a new tab and run the following subscription. You should see a ‘listening…’ message with a little spinning wheel. Over in another tab, we can now run any of our other past mutations and our subscription will automatically return what was done and what was changed.

localhost:4000我们可以打开一个新选项卡并运行以下订阅。 您应该会看到带有小旋转轮的“正在听……”消息。 在另一个选项卡上,我们现在可以运行我们过去的任何其他突变,并且我们的订阅将自动返回已完成和已更改的内容。

subscription {  user {    mutation    data {      name      age    }  }}

结论 (Conclusion)

I hope this was helpful in understanding how to setup your GraphQL APIs with Mutations and Subscriptions. If there were any problems in setting this up, you can always check out .

我希望这对了解如何使用突变和订阅设置GraphQL API有所帮助。 如果在设置时遇到任何问题,您可以随时查看 。

翻译自:

vue中的突变方法在哪

转载地址:http://qshgb.baihongyu.com/

你可能感兴趣的文章
WPF进阶教程 - 使用Decorator自定义带三角形的边框
查看>>
SQLServer之FOREIGN KEY约束
查看>>
redis 系列2 知识点概述
查看>>
图像滤镜艺术---图像滤镜晕影调节算法研究
查看>>
Win8Metro(C#)数字图像处理--2.21二值图像腐蚀
查看>>
MVC5 + EF6 入门完整教程
查看>>
SQL Server如何在变长列上存储索引
查看>>
Replication的犄角旮旯(八)-- 订阅与发布异构的问题
查看>>
Sliverlight实例之 绘制扇形和环形图
查看>>
Visual Studio 2012使用水晶报表Crystal Report
查看>>
你不知道的 页面编码,浏览器选择编码,get,post各种乱码由来
查看>>
SQLSERVER PRINT语句的换行
查看>>
Windows 8.1 应用开发 – 触控操作
查看>>
PowerDesigner创建物理模型
查看>>
使用Git、Git GUI和TortoiseGit
查看>>
vue---canvas实现二维码和图片合成的海报
查看>>
检查项目里是否有IDFA的方法
查看>>
64位系统使用Access 数据库文件的彻底解决方法
查看>>
注释,字符串
查看>>
性能瓶颈
查看>>