Skip to content

Mutation

Rishabh kohale edited this page Nov 3, 2019 · 1 revision

Here we will see how to write the mutations properly:

Step 1:

Define the Mutation in the schema.graphql with properly defined input (if any and which can be an Object Entity or single attribute like string, number, etc), and the Entity ( object, number, string, boolean, etc) that needs to be returned.

exampleMutation(input: ExampleMutationInput): ReturnEntity
  • exampleMutation is the name of the mutation (which can be anything of your choice, but well, try to keep it related to the context to avoid confusion (We do not want a horse mutation creating a monkey. Lol.).
  • ExampleMutationInput is the input type which can be anything from string to boolean or number or even user-defined object.
  • Suppose it is an user defined object, we need to define it in the same file as follows:
input ExampleMutationInput {
  inputA: inputAtype!
  inputB: inputBtype
  inputC: [inputCtype]
}
  • The ! means that we cannot skip this input, else not necessary for proper execution.
  • The input-types can again be string, boolean, number, user-defined object, etc. or even array which is shown by [ ].
  • ReturnEntity can be anything like string, boolean, number, user-defined object, array, etc. Suppose it is user-defined, it first needs to defined as follows:
type ReturnEntity {
  inputA: inputAtype!
  inputB: inputBtype
  inputC: [inputCtype]
}

Notes:

  • Keep in mind to use type and input keywords appropriately.
  • It is preferable to use user-defined entity for input even if it has one attribute. It'll help extend the no of input attributes in future if necessary, without changing the mutation.

Step 2:

Now the functioning of the mutation needs to defined in the resolver.ts(/.js) under the Mutation keyword/object with the same name as the one defined in the schema.graphql.

async exampleMutation(obj: any, { input }: any, context: any)
{
   // some logic checks and function calls defined in sql.ts(/.ts) of that module for database actions
   return ReturnEntity
}
  • Here async is optional and is used for proper flow of actions.
  • exampleMutation is the name of the mutation
  • input is of type ExampleMutationInput

Step 3:

Now define the functions required for the database action for that mutation in the sql.ts(/.ts) file in that module within proper class.

Now the mutation can be used in the client side