2024-06-21
In this blog we will group our arguments using inputType and then use it to write the mutation.
Blog post by MF Mabala
Using InputType for pothos Mutation
When developing apps that consist of the frontend and backend there is a query language that you will use. I prefer to use GraphQL Pothos ,you can use any that you feel comfortable with . Normally When we write the mutation we will define the arguments individually and use them individually. There are other different ways to define arguments and in this blog we will learn about input type.
Input type
Input type -is a special object type that groups a set of arguments together, and can then be used as an argument to another field. We often use input types when writing mutations. it helps us better understand our arguments. Here is an example of how we can use the input type
Defining the input type
Lets say you have an application that your subscribers and staff members can use. You want to be able to suspend a user from the app. We can define a mutation for that functionality in our Pothos schema. Let us start by defining our input type below
const SuspendUserInput = builder.inputType('SuspendUserInput', {
fields: (t) => ({
userId: t.id({ required: true }),
tenantId: t.id({ required: true }),
reason: t.string({ required: true }),
}),
});
Now that we have defined the input type we can now write the mutation as follows
builder.mutationField('suspendUser', (t) =>
t.field({
shield: isTenantAdmin,
description: 'Suspend user',
type: UserSchema,
args: {
input: t.arg({ type: SuspendUserInput, required: true }),
},
resolve: async (_root, args, ctx) => {
const user = await suspendUser(
{ ...args, userId: args.input.userId.toString(), tenantId: args.input.tenantId.toString() },
ctx
);
return user;
},
})
);
Adding the mutation to the frontend.
Defining a mutation on the api(backend) is important has to be also defined or called in the app(frontend) for it to function when our app when accessed by the user. Go to your graphQL file on the frontend where you want to add the mutation . See an example below
input SuspendUserInput {
userId: ID!
tenantId: String!
reason: String!
}
mutation SuspendUser($input: SuspendUserInput!) {
suspendUser(input: $input) {
status
}
}
After this you are good to add more functionality to your frontend so that your suspend user feature can work. You can add hooks and components...