Custom Mutations
As a product gets more complicated, the need to eventually add custom mutations to the schema arises. This shows how to do so.
Auth Example
A common thing for a lot of applications is to implement authentication to log the user in. This shows a possible way to implement it:
@gqlInputObjectType()
export class UserAuthInput {
@gqlField()
emailAddress: string;
@gqlField()
password: string;
}
@gqlObjectType()
export class UserAuthPayload {
@gqlField({ type: GraphQLID })
viewerID: ID;
}
export class AuthResolver {
@gqlMutation({ name: "userAuth", type: UserAuthPayload })
async userAuth(
@gqlContextType() context: RequestContext,
@gqlArg("input") input: UserAuthInput,
): Promise<UserAuthPayload> {
return {viewerID : "1"};
}
}
This updates the GraphQL schema as follows:
type Mutation {
userAuth(input: UserAuthInput!): UserAuthPayload!
}
type UserAuthPayload {
viewerID: ID!
}
input UserAuthInput {
emailAddress: String!
password: String!
}
Here's what's happening here:
- This adds a new input type
UserAuthInput
to the GraphQLSchema represented by the classUserAuthInput
. UserAuthInput
object has 2 fields:emailAddress
of typeString
password
of typeString
- This adds a new object type
UserAuthPayload
to the GraphQLSchema represented by the classUserAuthPayload
UserAuthPayload
object has 1 field:viewerID
of typeID
- New field
userAuth
added toMutation
Type which takesUserAuthInput
input and returnsUserAuthPayload
.
This uses the following concepts to implement this:
gqlMutation
This adds a new field to the GraphQL Mutation
type. See example usage above.
Accepts the following options which overlap with gqlField:
name
for the name of the GraphQL fielddescription
of the fieldtype
: type returned by the field
gqlInputObjectType
Adds a new input object to the schema. See example usage above.
Options:
name
Name of the input object. If not specified, defaults to the name of the class.
description
Description nof the input object. Will be added to the Schema and exposed in tools like GraphiQL or Playground.
gqlObjectType
Adds a new object to the schema. See example usage above.
Options:
name
Name of the object. If not specified, defaults to the name of the class
description
Description nof the object. Will be added to the Schema and exposed in tools like GraphiQL or Playground.