Angular Apollo: Mutations, Queries, Subscriptions, And Fragments
Published: 2024-01-19 14:33:36

One of the most important concepts to understand in Angular is the angular Apollo, how they work, and how to use them in your code.The Angular website has some extensive documentation on Apollo, but in this blog I plan to cover the basics of its usage and what you need to know to begin working with  Angular Apollo.

## Introduction to Angular Apollo 
GraphQL Apollo Angular is the ultra-flexible, community-driven client for Angular, JavaScript, and native platforms. You should use Apollo Client with one of its view layer integrations to get the most value out of it. It is designed from the ground up so that you can easily build UI components with GraphQL.

## Installation
The simplest way to get started with Apollo Angular is by running ng add apollo-angular command.

## Installation with Angular Schematics
To start using Apollo Angular simply run:
`ng add apollo-angular`

##  Queries
Queries are the one of the first things we learn about in GraphQL.
When combined with great tooling, GraphQL's declarative approach to requesting data makes query-writing an enjoyable experience.

## What do GraphQL queries look like?
Here’s an example of a GraphQL query written three different ways.

```ts
 GraphQL query with the query and name keywords
query GetPets {
  pets {
    name 
    petType
  }
}

 GraphQL query with just the query keyword
query {
  pets {
    name
    petType
  }
}

GraphQL query with neither the query or name keyword
{
  pets {
    name 
    petType
  }
```}

Functionally, all three queries are equivalent.
However, it's recommended to use both query and name keywords anyway to:
- Identify the type of operation
- Make it easier for your team mates to understand what your query is about
In the query examples above, we ask for the name and petType fields, which are subfields of the pets type.

## How to execute GraphQL queries
When we write a query, we know what to expect in response. The next question is, how do we execute it?
GraphQL queries are just plain strings, so we can use a number of approaches to fetch data. Some options include:
- Curl 
- Fetch
- Client libraries for GraphQL (such as Apollo Client)
- A GraphQL IDE is another option

## 
Why GraphQL queries
Angular Apollo uses queries to get information from your GraphQL server for several reasons:

**1.  Fetching Data:**
Queries are used when you need to display information on your Angular app, such as a list of products, user details, or recent orders.

**2.  Identifying the information you need:**
By specifying which fields you want from a particular type in your GraphQL schema, you avoid unnecessary data transfer and improve performance.

**3. Retrieval of dynamic data:**
If you use variables in your queries, you can retrieve data based on user input, selected filters, or other conditions

**4. Combining data from multiple sources:**
A GraphQL query allows you to combine data from multiple types in your schema and present it in a cohesive way.

**5. The cache:**
It is possible to cache queries, which means that the data they retrieve can be stored locally for faster access and improved performance.

## When to use Queries
Querying might be useful in the following scenarios:
- On a product page, a list of products is displayed
- Profile view showing user details.
- Using user input to filter products
- A user's recent orders are retrieved.
- A particular blog post's comments are loading.

Angular Apollo queries provide a powerful and flexible way to get the exact information you need to build engaging and dynamic applications. They offer a powerful and flexible way to get the exact information you need.

## Mutations:
GraphQL mutations are operations that modify information on the server. Unlike queries, mutations actively rewrite the story, adding, updating, or deleting specific elements.

**How to Use Mutations:**
It involves writing specific instructions that tell your server what to do. These instructions include:
**1.Type definition:** You specify what you want to change, such as "Product" or "User."
**2.Select the desired action:** "create," "update," or "delete."
**3.Parameters:**Please provide details about the change, such as the product name, the user's email address, or the data to be removed.
Once you send these instructions, your server performs the transformation and sends back confirmation. Boom! Your data is mutated.

**When to Use Mutations:**
Mutations are used when:
**1.Create new data:**Post a comment, add a new product, or register a new user.

```ts
mutation CreatePost($title: String!, $content: String!) {
  createPost(title: $title, content: $content) {
    id
    title
    createdAt
  }
```}


**2.Update existing data:**You can edit existing data by changing the price of a product, editing the information of a user, or marking an order as completed.

```ts
mutation UpdateProductPrice($id: ID!, $price: Float!) {
  updateProduct(id: $id, price: $price) {
    id
    name
    price
  }
```}

**3.Delete data:** Deactivate an account, remove unwanted comments, or remove outdated products

```ts
mutation DeleteUser($id: ID!) {
  deleteUser(id: $id)
```}

**Why Use Mutations?**
Here's why mutations are valuable tools:

**- Direct manipulation:** They directly change data, unlike the passive retrieval of queries.
**- Precise control:** You specify exactly what you want to modify, minimizing unintended changes.
**- Real-time updates:** Data changes on your server are reflected immediately in your app.
**- Flexibility:** They handle diverse actions like creating, updating, and deleting across different types.

## Subscriptions:
Subscriptions  are operations in GraphQL that establish a persistent connection to your server, enabling you to receive real-time updates whenever relevant data changes.

**How to Use Subscriptions:**
Here's how to establish a subscription:

**1.Define Your Interest:** Specify the fields you want to receive updates for, like new messages, updated stock prices, or live chat notifications.
**2.Establish the Connection:** Your client establishes a WebSocket connection with your GraphQL server, creating a direct channel for real-time data flow.
**3.Listen for Updates:**Your server sends updates whenever relevant changes occur, and your client receives and processes them, updating your app's UI or triggering actions accordingly.

**When to Use Subscriptions:**
Consider subscriptions when:
**1.Collaborative Features:** Building live chat, collaborative editing, or real-time notifications.
**2.Live Updates**: Displaying live sports scores, stock prices, or news feeds.
**3.Instant Feedback:** Providing immediate responses to user actions, like order confirmations or payment processing.
**4.Enhanced User Experience:** Creating a more dynamic and responsive user experience

**Why Use Subscriptions?**
Here's why subscriptions matter:
**1.Real-Time Synchronization:** Keep your app in perfect sync with the server, eliminating manual refreshes.
**2.Enhanced User Engagement:** Facilitate instant interactions and create more engaging experiences.
**3.Improved Efficiency:**Reduce server load and improve responsiveness by avoiding unnecessary polling.
**4.Optimized Data Transfer:** Transmit only relevant updates, reducing bandwidth usage

**Example Code:**
**GraphQL Subscription:**

```ts
subscription NewChatMessage {
  newChatMessage {
    sender
    message
    createdAt
  }
```}

**Implementation in Angular Apollo:**

```ts
import { Apollo, gql } from 'apollo-angular';

const CREATE_POST_MUTATION = gql
  mutation CreatePost($title: String!, $content: String!) {
    createPost(title: $title, content: $content) {
      id
      title
      createdAt
    }
  }
;

// ...

constructor(private apollo: Apollo) {}

createPost(title: string, content: string) {
  this.apollo
    .mutate({
      mutation: CREATE_POST_MUTATION,
      variables: { title, content },
    })
    .subscribe(({ data }) => {
      console.log('Post created:', data.createPost);
    });
```}

## Fragments:
Fragments are essentially bundles of fields that serve as mini GraphQL queries for future use. As a replacement for repeating the same fields across multiple queries, fragments allow you to create one and then include it wherever needed.

**How to Use Fragments:**
Here's how to craft and utilize fragments:
**1.Define Your Gem:** Give your fragment a name and specify the fields you want to include, like a recipe for sparkling success.
**2.Place Your Gems:** Use the fragment keyword and your chosen name where you want to include the snippet, like inserting a gem into your jewelry design.
**3.Shine Brighter:** Reap the benefits of reusability, consistency, and reduced code complexity, enhancing your GraphQL code like a dazzling masterpiece

**When to Use Fragments:**
We can use fragments when:
**1.Repeated Field Sets:** You have the same group of fields appearing in multiple queries or mutations.
**2.Modular Design:**You want to break down your queries into smaller, reusable components.
**3.Code Maintenance:** You need to make changes in one place and have them reflected everywhere the fragment is used.
**4.Improved Readability:** You want to make your code cleaner and easier to understand.

**Why Use Fragments?**
Here are some reason why we use fragments :
**1.Reduced Duplication:** Eliminate repetitive code, minimizing redundancy and increasing maintainability.
**2.Modular Approach:** Promote modularity and componentization, making your code easier to manage.
**3.Improved Readability:**Enhance code clarity by using descriptive names and avoiding verbose field repetitions.
**4.Consistency:**Ensure the same field selection is used everywhere, guaranteeing consistent data retrieval.

**Code Example**
**GraphQL Fragment:**

```ts
fragment UserAvatar on User {
  avatarUrl
  avatarSize
```}

**Query with Fragment:**

```ts
query GetUserWithAvatar($id: ID!) {
  user(id: $id) {
    ...UserAvatar
    email
    firstName
  }
```}

## In conclusion
In the complex realm of data management, Angular Apollo provides a robust set of resources. We have examined four key instruments – mutations, queries, subscriptions, and fragments – each serving distinct purposes and playing vital roles in shaping your data framework.
So, embrace the power of Angular Apollo, wield your knowledge of mutations, queries, subscriptions, and fragments, and embark on a journey of building truly exceptional applications!

Dive deeper into the world of Angular Apollo with these resources:
Official Documentation: https://the-guild.dev/
https://www.apollographql.com/blog/what-is-a-graphql-query-graphql-query-using-apollo-explorer
https://www.apollographql.com/docs/react/data/mutations/
Tutorial: https://m.youtube.com/watch?v=dp_64aX_6jI
GraphQL Cheat Sheet: https://www.apollographql.com/docs/apollo-server/schema/schema/







```