GraphQL - Is it possible to set a variable with a result for a mutation - graphql

I want to do 2 creations in my GraphQL query. (I know my query structure is not correct, but it's to illustrate my question)
mutation {
affiliateCreate(company: "test mutation") {
$id: id,
affiliateUserCreate(affiliate_id: $id, name: "test name") {
id,
name
},
company
}
}
I want my first id result to be in variable who i pass to the second creation call? I'm very new to GraphQL and i was wondering if it's possible.
Is there any other way possible to do such thing? Or i must do 2 mutation call? The first with affiliateCreate and in it's fallback the second one?
Thank you

What you want to do is not supported by GraphQL. In the Graphcool APIs we approach this kind of situation with what we call nested mutations. I've also heard it being referred to as complex mutations.
A nested create mutation is characterized by a nested input object argument. If you add an input object author to the affiliateCreate mutation, you could use it like that:
mutation createAffiliateAndUser {
affiliateCreate(
company: "test company"
author: {
name: "test user"
}
) {
id
}
}
This would create an affiliate, a user and then link the two together. Similarily, if you add an input object affiliates to the userCreate mutation, it could look like this:
mutation createUserAndAffiliates {
userCreate(
name: "test user"
affiliates: [{
company: "first company"
}, {
company: "second company"
}]
) {
id
}
}

Related

How to create GraphQL Child Resolvers with Lambda

I'm trying to create a mutation that calls a child resolver in addition to the parent resolver if an optional parameter is sent in.
I'm using AWS AppSync to sent my queries to Lambda. AppSync creates and sends an AppSyncEvent to my resolver file that looks something like this:
{
"info": {
"parentTypeName": "Mutation",
"selectionSetList": [
...
],
"selectionSetGraphQL": "...",
"fieldName": "updateUser",
"variables": {}
}
}
This event gets passed to my lambda function where, based on the fieldName and parentTypeName, I call my updateUser function.
I have the below schema
schema {
query: Query
mutation: Mutation
}
type Query {
getUser(id: ID!): User
}
type Mutation {
updateUser(name: String, email: String, bookRead: BookReadInput): User
}
type User {
name: String
email: String
booksRead: [Book]
}
type Book {
title: String
author: String
}
type BookReadInput {
title: String
author: String
}
I want that if the mutation gets passed bookRead then it will know to call a child resolver called addBook besides for the regular updateUser resolver.
I've seen various articles about implementing child resolvers but I can't figure out how they can work with lambda and the way my resolvers work.
The lambda could inspect the selectionSetList and decide what to do with the BookReadInput fields.
See https://aws.amazon.com/blogs/mobile/appsync-and-the-graphql-info-object/
You could also go with pipeline resolvers to first update the user, and then add the book.
I don't think there is a way to have it automated. You need to set it up, one way or the other.

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.

Laravel Lighthouse GraphQL create mutation without "input:"

I'm looking a the documentation for Laravel Lighthouse and I am seeing two types of mutations.
A mutation that includes the string input: (found here)
mutation {
createPost(input: { # <-- the "input:" I'm talking about
title: "My new Post"
author: {
connect: 123
}
}){
id
author {
name
}
}
}
And another mutation without the input: (found here)
mutation CreateTaskWithNotes {
createTask( # <-- no "input:" here
id: 45
name: "Do something"
notes: [
{
content: "Foo bar",
link: "http://foo.bar"
},
{
content: "Awesome note"
}
]
) {
id
}
}
My question is: How do I get the mutations without input: to work?
I try to copy (an modify) the examples from the documentation. But if I write a mutation like this:
type Mutation {
createTask(input: CreateTaskInput! #spread): Task! #create
}
When I try to omit input:, graphql-playground complains: "Field createTask argument input of type CreateTaskInput is required but not provided"
Now I try to change the schema to this:
type Mutation {
createTask(CreateTaskInput! #spread): Task! #create
}
But then the server gives a ParseException.
I do prefer the syntax without input: because that is a lot less repetitive.
Can anybody help?
If you want to write a mutation without the input, also ommit the #spread directive. So:
type Mutation {
createTask(
id: ID
name: String
): Task! #create
}
But I think it's a "best practices" to have that inside an input. Of course you can do wethever you want to do.
Try this
type Mutation {
createTask: Task! #create
}
https://newbedev.com/index.php/graphql-mutations-without-arguments

Cannot perform update query because update values are not defined

I am trying to execute a mutation like so
mutation creating {
createTeam(
payload: {
name: "Team von abc"
tacts:["94b4cbc2-b996-482f-b712-967bdb646e73"]
}
) {
id
name
}
}
This results in :
"message": "Cannot perform update query because update values are not
defined. Call \"qb.set(...)\" method to specify updated values.",
My graphql is defined like this:
input CreateTeamPayload {
name: String
tacts:[ID!]
}
type Team {
id: ID!
name: String
tacts: [Tact]!
}
type Query {
fetchTeams: [Team]!
fetchTeamById(id: ID!): Team
}
type Mutation {
createTeam(payload: CreateTeamPayload): Team!
}
My Team requires an ID from a "tact" so I provide him with an ID from a "tact" I created before. Is this approach wrong? How can I mutate types that reference other types? is there some documentation that actually does this?

Validation error of type UndefinedFragment: Undefined fragment

I've a graphql-jave v8.0 app running on Spring boot v1.5.10, and I'm trying to utilize 'fragment' feature of GraphQL to fetch limited number of fields with the following schema type definition:
type School {
id: ID
name: String
address: String
age: String
jobTitle: String
...
}
fragment UserFields on School {
age
jobTitle
}
type Query {
user (id: String!): School!
}
schema {
query: Query
}
When I execute this query:
{
user (id: "123")
{
... UserFields
}
}
The expected result should be:
{
"user": {
"age": "12",
"jobTitle": "student"
}
}
However, It results in the following error
"message": "Validation error of type UndefinedFragment: Undefined fragment
UserFields # 'user'",
Off course I can do this with explicitly passing the field name in the query but for the sake of example, I'm interested in utilizing fragment feature of GraphQL.
Any idea what I'm doing wrong please?
Fragments aren't defined in the schema, they're something for letting you create abstractions whilst building complex queries -- the main purpose is to allow you to avoid repetition when querying the same type in multiple parts of your query.
As Andrew said, and as the official docs exemplify, fragments are not defined in the schema but (ad hoc) in the query:
{
user (id: "123") {
... UserFields
}
}
fragment UserFields on School {
age
jobTitle
}
Unconditional fragments (like the one here) are used to avoid repetition. Imagine having multiple places where you want to select age and jobTitle in the same operation.
Conditional fragments, on the other hand, are used to make a conditional selection depending on the concrete interface implementation or union subtype.

Resources