Skip to main content

Generated Code

Let's examine the code generated by the following GraphQL operations:

book.graphql
fragment BookFragment on Book {
id
name
genre
authorId
}

query Books($name: String, $genre: String, $authorId: ID) {
books(name: $name, genre: $genre, authorId: $authorId) {
...BookFragment
}
}

mutation UpdateBook($id: ID!, $book: BookInput!) {
updateBook(id: $id, book: $book) {
...BookFragment
}
}

Query

One of the main elements of the generated code is BooksQuery class:

export class BooksQuery extends PureQueryOptions<BooksQueryData, BooksQueryVariables> {
public constructor(variables?: BooksQueryVariables, context?: Context) {
super(BooksDocument, variables, context);
}
}

This class is generated for Books GraphQL query and accepts an optional query variables constructor parameter and can be used to query data as follows:

protected readonly booksQuery: BooksQueryObservable = this.apollo.watchQuery(new BooksQuery({ genre: 'Fiction' }));
// OR
protected readonly booksQuery: QueryResult<BooksQueryData> = this.apollo.query(new BooksQuery({ genre: 'Fiction' }));

An instance of BooksQuery has the following properties:

{ query: BooksDocument, variables?: BooksQueryVariables, context?: { [key: string]: any } }

BooksQueryObservable is a helper type alias generated for QueryObservable<BooksQueryData, BooksQueryVariables>

Mutation

Secondly, we have UpdateBookMutation class:

export class UpdateBookMutation extends PureMutationOptions<UpdateBookMutationData, UpdateBookMutationVariables> {
public constructor(variables: UpdateBookMutationVariables, context?: Context) {
super(UpdateBookDocument, variables, context);
}
}

This class is generated for UpdateBook GraphQL mutation and accepts a mandatory mutation variables constructor parameter and can be used to execute a mutation as follows:

protected updateBook(id: string, book: BookInput): void {
this.apollo.mutate(new UpdateBookMutation({ id, book })).subscribe();
}

An instance of UpdateBookMutation has the following properties:

{ mutation: UpdateBookDocument, variables: UpdateBookMutationVariables, context?: { [key: string]: any } }

UpdateBookMutationInfo is a helper type alias generated for MutationInfo<UpdateBookMutationData, UpdateBookMutationVariables> which can be used in state definitions.

info

Note that UpdateBookMutation class constructor accepts a mandatory variables parameter as opposed to BooksQuery which accepts an optional parameter.
This is automatically determined by codegen when variables have a mandatory field, in order to provide compile time safety, ensuring that variables are always provided when required by the GraphQL schema.