How to chain mutations in apollo-client while using a form component - apollo-client

Apollo-Client 2.0. I am using chained Mutation components. I am trying to pass a returned value from the first Mutation to the second Mutation. I execute the mutations when an onSubmit button is clicked on a form component. The returned value from first mutation is not being passed as one of the "variables" in second mutation
I reviewed solutions in two very similar posts: How to wrap GraphQL mutation in Apollo client mutation component in React and How to chain together Mutations in apollo client. I think my use of a form is adding some additional complexity to my solution. Although the passed value (competitionId) is visible in the handleOnSubmit function (if I console log after createCompetition() in handleOnSubmit), it is not getting passed as a variable in the second Mutation which is called in the handleOnSubmit. The result is a successful execution of the first Mutation and a 400 error on the second mutation: “errors”:[{“message”:“Variable \“$competitionId\” of required type \“ID!\” was not provided.” To be more specific, the value of CompetitionId DOES get passed to the second mutation after the first mutation runs, but it does not get passed as a "variables" to the createMatch function passed as an argument to the handleOnSubmit. It looks like the "variables" passed along with the createMatch function to the handleOnSubmit, only include the variables that are available when the submit button is clicked. The competitionId, is generated after the submit button is clicked and the first mutation returns it as a result.
handleOnSubmit = async(event, createCompetition, createMatch) => {
event.preventDefault();
await createCompetition();
await createMatch();
this.clearState();
this.props.history.push('/home');
}
render () {
const {location, name, action, caliber, rifleName, dateOf,competitionScore} = this.state;
const { matchNumber, targetNumber, relay, distanceToTarget, matchScore} = this.state;
return (
<div className="App">
<h2 className="App">Add Competition</h2>
<Mutation
mutation={CREATE_COMPETITION}
variables={{location, name, action, caliber, rifleName, dateOf, competitionScore}}
refetchQueries={() => [
{ query: GET_ALL_COMPETITIONS, variables:{name: name}}
]}
update={this.updateCache}>
{(createCompetition, {data, loading, error}) => {
if(loading) return <div>loading competition...</div>
if(error) return <div>error: {error}</div>
let competitionId;
if(data) {
competitionId = data.createCompetition._id;
}
return (
<Mutation
mutation={CREATE_MATCH}
variables={{competitionId, matchNumber, targetNumber, distanceToTarget, matchScore}}>
{(createMatch, {_, loading, error}) => {
if(loading) return <div>loading match...</div>
return (
<form
className="form"
onSubmit={event => this.handleOnSubmit (event, createCompetition, createMatch)}>
<label> remaining form deleted for brevity
I expected the value of the CompetitionId to be passed as a variable to the createMatch function called in the handleOnSubmit method. It is not provided.

Seems what you needs is nested mutations :thinkingface;
Q: Are you using prisma?
Well, in GraphQL you can create nodes by a single mutation, this is pretty simple if your Types are related, so I assume this is your case.
And should looks something like this:
datamodel.graphql
type Competition {
id: ID! #unique
name: String!
match: Match! #relation(name: "CompetitionMatch")
}
type Match {
id: ID! #unique
name: String!
campetition: Competition! #relation(name: "CompetitionMatch")
}
So, now in your schema.graphql should looks like this:
type Mutation {
createCompetition (name: String! match: MatchInput): Competition
}
input MatchInput {
name: String!
}
and now when you call your createCompetition mutation, you have to send the match data, like so:
mutation createCompetition (
name: 'Loremp competition'
match: { name: 'child match'}
) {
id
name
match {
id
name
}
}
Ref: https://www.graph.cool/docs/reference/graphql-api/mutation-api-ol0yuoz6go/#nested-create-mutations
Hope this help!
regards

Where the if (data) is, is where you should return the 2nd mutation

Related

KeystoneJS relationships, how can I connect using an array of ids

I am using the new version Keystone Next and I am trying to connect multiple items at once using an array of ids. It seems connect supports that, accepting an array of objects.
const FINISH_VOCABULARY_QUIZ_MUTATION = gql`
mutation FINISH_VOCABULARY_QUIZ_MUTATION(
$userId: ID!
$wordId: ID!
) {
updateUser(id: $userId, data: {
wrongAnswers: {
connect: [{id: "idblabla"}, {id: "idblabla2"}]
}
}) {
id
}
}`;
But what I just can't seem to figure out is how do I pass this array of ids as a variable to my mutation.
I understand that I would need to create a new type? The documentation is still unfinished, so there is nothing on that yet.
I have also tried using string interpolation to form my query, but it seems that it's not a thing in GraphQl.
This is more of a GraphQL question than a KeystoneJS but one but to head to the right direction here you'd need to change your query to something like below:
const FINISH_VOCABULARY_QUIZ_MUTATION = gql`
mutation FINISH_VOCABULARY_QUIZ_MUTATION(
$userId: ID!,
$ids: [UserWhereUniqueInput!]!
) {
updateUser(id: $userId, data: {
wrongAnswers: {
connect: $ids
}
}) {
id
}
}`;
And then map your array of ids to an array of objects with id fields.
There is a better method:
const FINISH_VOCABULARY_QUIZ_MUTATION = gql`
mutation FINISH_VOCABULARY_QUIZ_MUTATION(
$userId: ID!,
$data: SomeAPIDefinedMutationUniqueInput
) {
updateUser(id: $userId, data: $data)
id
}
}`;
This way you:
don't have to define types for internal arguments ($wordsIdWrong: [WordWhereUniqueInput]);
can reuse/share this mutation - import it from some, common for queries, place (dir) - just call it with different data variables;
easier for reading/maintenance;
PS. To be honest, there should be some specific [to quizes] mutation (don't use userUpdate for that), with user (or better quiz) id defined within SomeAPIDefinedUniqueInput.

Can Apollo read partial fragments from cache?

I have a simple mutation editPerson. It changes the name and/or description of a person specified by an id.
I use this little snippet to call the mutator from React components:
function useEditPerson(variables) {
const gqlClient = useGQLClient();
const personFragment = gql`fragment useEditPerson__person on Person {
id
name
description
}`;
return useMutation(gql`
${personFragment}
mutation editPerson($id: ID!, $description: String, $name: String) {
editPerson(id: $id, description: $description, name: $name) {
...useEditPerson__person
}
}
`, {
variables,
optimisticResponse: vars => {
const person = gqlClient.readFragment({
id: vars.id,
fragment: personFragment,
});
return {
editPerson: {
__typename: "Person",
description: "",
name: "",
...person,
...vars,
},
};
},
});
}
This works well enough unless either the name or description for the indicated person hasn't yet been queried and does not exist in the cache; in this case person is null. This is expected from readFragment - any incomplete fragment does this.
The thing is I really need that data to avoid invariant errors - if they're not in the cache I'm totally okay using empty strings as default values, those values aren't displayed anywhere in the UI anyway.
Is there any way to read partial fragments from the cache? Is there a better way to get that data for the optimistic response?
I guess you use the snippet in the form that has all the data you need. So, you can pass the needed data to your useEditPerson hook through the arguments and then use in optimistic response, and then you won't need to use gqlClient.

FaunaDB - How to bulk update list of entries within single graphQL mutation?

I want to bulk update list of entries with graphQL mutation in faunaDB.
The input data is list of coronavirus cases from external source. It will be updated frequently. The mutation should update existing entries if the entry name is present in collectio and create new ones if not present.
Current GRAPHQL MUTATION
mutation UpdateList($data: ListInput!) {
updateList(id: "260351229231628818", data: $data) {
title
cities {
data {
name
infected
}
}
}
}
GRAPHQL VARIABLES
{
"data": {
"title": "COVID-19",
"cities": {
"create": [
{
"id": 22,
"name": "Warsaw",
"location": {
"create": {
"lat": 52.229832,
"lng": 21.011689
}
},
"deaths": 0,
"cured": 0,
"infected": 37,
"type": "ACTIVE",
"created_timestamp": 1583671445,
"last_modified_timestamp": 1584389018
}
]
}
}
}
SCHEMA
type cityEntry {
id: Int!
name: String!
deaths: Int!
cured: Int!
infected: Int!
type: String!
created_timestamp: Int!
last_modified_timestamp: Int!
location: LatLng!
list: List
}
type LatLng {
lat: Float!
lng: Float!
}
type List {
title: String!
cities: [cityEntry] #relation
}
type Query {
items: [cityEntry!]
allCities: [cityEntry!]
cityEntriesByDeathFlag(deaths: Int!): [cityEntry!]
cityEntriesByCuredFlag(cured: Int!): [cityEntry!]
allLists: [List!]
}
Everytime the mutation runs it creates new duplicates.
What is the best way to update the list within single mutation?
my apologies for the delay, I wasn't sure exactly what the missing information was hence why I commented first :).
The Schema
An example of a part of a schema that has arguments:
type Mutation {
register(email: String!, password: String!): Account! #resolver
login(email: String!, password: String!): String! #resolver
}
When such a schema is imported in FaunaDB there will be placeholder functions provided.
The UDF parameters
As you can see all the function does is Abort with the message that the function still has to be implemented. The implementation starts with a Lambda that takes arguments and those arguments have to match what you defined in the resolver.
Query(Lambda(['email', 'password'],
... function body ...
))
Using the arguments is done with Var, that means Var('email') or Var('password') in this case. For example, in my specific case we would use the email that was passed in to get an account by email and use the password to pass on to the Login function which will return a secret (the reason I do the select here is that the return value for a GraphQL resolver has to be a valid GraphQL result (e.g. plain JSON
Query(Lambda(['email', 'password'],
Select(
['secret'],
Login(Match(Index('accountsByEmail'), Var('email')), {
password: Var('password')
})
)
))
Calling the UDF resolver via GraphQL
Finally, how to pass parameters when calling it? That should be clear from the GraphQL playground as it will provide you with the docs and autocompletion. For example, this is what the auto-generated GraphQL docs tell me after my schema import:
Which means we can call it as follows:
mutation CallLogin {
login (
email: "<some email>"
password: "<some pword>"
)
}
Bulk updates
For bulk updates, you can also pass a list of values to the User Defined Function (UDF). Let's say we would want to group a number of accounts together in a specific team via the UI and therefore want to update multiple accounts at the same time.
The mutation in our Schema could look as follows (ID's in GraphQL are similar to Strings)
type Mutation { updateAccounts(accountRefs: [ID]): [ID]! #resolver }
We could then call the mutation by providing in the id's that we receive from FaunaDB (the string, not the Ref in case you are mixing FQL and GraphQL, if you only use GraphQL, don't worry about it).
mutation {
updateAccounts(accountRefs: ["265317328423485952", "265317336075993600"] )
}
Just like before, we will have to fill in the User Defined Function that was generated by FaunaDB. A skeleton function that just takes in the array and returns it would look like:
Query(Lambda(['arr'],
Var('arr')
))
Some people might have seen an easier syntax and would be tempted to use this:
Query(Lambda(arr => arr))
However, this currently does not work with GraphQL when passing in arrays, it's a known issue that will be fixed.
The next step is to actually loop over the array. FQL is not declarative and draws inspiration from functional languages which means you would do that just by using a 'map' or a 'foreach'
Query(Lambda(["accountArray"],
Map(Var("accountArray"),
Lambda("account", Var("account")))
))
We now loop over the list but don't do anything with it yet since we just return the account in the map's body. We will now update the account and just set a value 'teamName' on there. For that we need the Update function which takes a FaunaDB Reference. GraphQL sends us strings and not references so we need to transform these ID strings to a reference with Ref as follows:
Ref(Collection('Account'), Var("account"))
If we put it all together we can add an extra attribute to a list of accounts ids as follows:
Query(Lambda(["accountArray"],
Map(Var("accountArray"),
Lambda("account",
Do(
Update(
Ref(Collection('Account'), Var("account")),
{ data: { teamName: "Awesome live-coders" } }
),
Var("account")
)
)
)
))
At the end of the Map, we just return the ID of the account again with Var("account") in order to return something that is just plain JSON, else we would be returning FaunaDB Refs which are more than just JSON and will not be accepted by the GraphQL call.
Passing in more complex types.
Sometimes you want to pass in more complex types. Let's say we have a simple todo schema.
type Todo {
title: String!
completed: Boolean!
}
And we want to set the completed value of a list of todos with specific titles to true. We can see in the extended schema generated by FaunaDB that there is a TodoInput.
If you see that extended schema you might think, "Hey that's exactly what I need!" but you can't access it when you write your mutations since you do not have that part of the schema at creation time and therefore can't just write:
type Mutation { updateTodos(todos: [TodoInput]): Boolean! #resolver }
As it will return the following error.
However, we can just add it to the schema ourselves. Fauna will just accept that you already wrote it and not override it (make sure that you keep the required fields, else your generated 'createTodo' mutation won't work anymore).
type Todo {
title: String!
completed: Boolean!
}
input TodoInput {
title: String!
completed: Boolean!
}
type Mutation { updateTodos(todos: [TodoInput]): Boolean! #resolver }
Which means that I can now write:
mutation {
updateTodos(todos: [{title: "test", completed: true}])
}
and dive into the FQL function to do things with this input.
Or if you want to include the ID along with data you can define a new type.
input TodoUpdateInput {
id: ID!
title: String!
completed: Boolean!
}
type Mutation { updateTodos(todos: [TodoUpdateInput]): Boolean! #resolver }
Once you get the hang of it and want to learn more about FQL (that's a whole different topic) we are currently writing a series of articles along with code for which the first one appeared here: https://css-tricks.com/rethinking-twitter-as-a-serverless-app/ which is probably a good gentle introduction.

How to implement mutations with optional arguments in GraphQL?

I am learning about graphql, and went through the https://www.howtographql.com/graphql-js/3-a-simple-mutation/ tutorial, and was interested in what the implementation of the updateLink mutation as follows would look like.
type Query {
# Fetch a single link by its `id`
link(id: ID!): Link
}
type Mutation {
# Update a link
updateLink(id: ID!, url: String, description: String): Link
}
The reason I am asking this is that every other mutation implementation I have seen uses only NON-optional parameters. I am curious if there is a community-agreed-upon pattern for extracting and applying only the provided non-null arguments(url, description) from the given context and applying them to relevant the database record.
I have considered checking if each variable is null as follows, but this approach looks way messier than I would expect compared to the rest of the 'magic' and simplicity that Graphql provides.
updateLink(root, args, context) {
if (args.url == null && args.description == null){
return null
} else if (args.url == null) {
return context.prisma.updateLink({
id: args.id,
description: args.description
})
} else {
return context.prisma.updateLink({
id: args.id,
url: args.url
})
}
}
Please let me know if you found a cleaner way to extract and apply the optional arguments(url, description).
Another consideration I had was to make two separate update mutations as follows.
type Query {
# Fetch a single link by its `id`
link(id: ID!): Link
}
type Mutation {
# Update a link
updateLinkURL(id: ID!, url: String!): Link
updateLinkDescription(id: ID!, description: String!): Link
}
The thinking here was with limited arguments and a declarative mutation name, one could force the arguments to be Non-Null. The main issue here is that one can have many update methods for tables with many columns, this would also start to look messy.
FYI I am using prisma as my ORM.
const resolvers = {
Query: {
info: () => `This is the API of a Hackernews Clone`,
feed: () => links,
link: (parent, args) => {
// console.log(args)
return links.find((link) => link.id === args.id)
}
},
Link: {
id: (parent) => parent.id,
description: (parent) => parent.description,
url: (parent) => parent.url,
},
}

Ignore results from mutation query using apollo client?

I want to use graphql to trigger an addLicenseCodeOneTimeUsage action on a server. I don't know what the server will respond with and I don't need any response. As you can see I list no properties in addLicenseCodeOneTimeUsage{}.
const client = new ApolloClient({
link: link,
cache: new InMemoryCache(),
});
yield client.mutate({
/* tslint:disable */
mutation: gql`
}
mutation licensemutation($distributor: String!, $licenceType: String!, $duration: String!, $userId: String!) {
addLicenseCodeOneTimeUsage(distributor: $distributor, licenseType: $licenseType, duration: $duration, userId: $userId) {
}
}
`,
/* tslint:enable */
variables: {
userId: username,
distributor: distributor,
licenseType: licenseType,
duration: duration,
},
});
Does what I have written this far sound reasonable or do I have obvious misconceptions about how graphql works or how it should be used?
In the graphql string I don't define what information to receive. Is that syntax valid or do I need to explicitly state that I want to ignore results?
The mutation’s return type must define at least one field and you must select at least one field from it in the query. (See §2.3 of the spec.)
If you control both the server and the client and the mutation really returns nothing, you could define an artificial ok: Boolean! that’s always true. You might return something like a user object that contains a list of entitlements too, in which case you could just select (and ignore) the user ID.
I think this might be what ignoreResults is for.
ignoreResults - If true, the returned data property will not update with the mutation result.
So the mutation (with this option) would look like:
client.mutate({
mutation: MutationDocument
variables: {
userId: username,
distributor: distributor,
licenseType: licenseType,
duration: duration,
},
ignoreResults: true
});

Resources