本文共 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中使用Mutation
和Subscription
类型来操纵和观察数据的变化,而不仅仅是查询。 随时在发现更多内容。
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。
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
Besides our server setup we just have an empty users
array and a simple schema and resolver for returning all our users.
除了我们的服务器设置外,我们只有一个空的users
数组以及一个用于返回所有用户的简单架构和解析器。
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:
{ "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 }
返回我们的空数组。
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
输入。
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; } }}
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.
通过按名称搜索用户,我们将知道要删除或更新的项目。
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 }}
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
。 每当我们想要将某些内容连接到此订阅时,我们都将使用此事件名称。
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 } }}
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/