Integrating Apollo GraphQL Client for Angular Framework

GraphQL Client for Angular | Working with Apollo

Apollo Client is a JavaScript state management framework that allows you to manage both local and remote data using GraphQL. It may be used to fetch, cache, and alter application data while also automatically updating your UI. Apollo Client assists you in structuring code in a cost-effective, predictable, and declarative manner that is consistent with modern development techniques. Before integrating the Apollo GraphQL client for Angular applications, let’s review a short introduction to GraphQL and GraphQL Client.

Knowing more about GraphQL

GraphQL Client for Angular
Photo by Radowan Nakif Rehan on Unsplash

GraphQL is a query language for APIs. Like REST or other web service architectures, it’s an approach for developing APIs, and it gives more flexibility to the client to ask for and receive only the data the client needs. Since the client can query and receive specific data, there will be no over fetching or under fetching with GraphQL, thus making it more efficient.

Visit this blog(https://payodatechnologyinc.medium.com/traditional-rest-api-vs-graphql-what-you-need-to-know-700983ba273f) to know more about GraphQL.

GraphQL Client

To get the data into the frontend from the GraphQL server, it’s possible to use plain Javascript and HTTP requests. Then what is the use of the GraphQL client?

GraphQL Client reduces most manual work by sending queries and mutations directly without constructing HTTP requests, synchronizing data across multiple frontend components, and managing the cache.

The two major clients available are Apollo GraphQL client and Relay. The Apollo GraphQL client is community-driven and is available for most development platforms — Web(JS — React, Angular, Vue, etc.), iOS, and Android. On the other hand, Relay was created by Facebook, and it’s available only for the Web. This article focuses on how to use the Apollo GraphQL client with the Angular framework.

Read More,

Traditional REST API vs GraphQL: What you need to know

Getting Started with Apollo Angular

There are two ways to set up the Apollo client. One with the help of Angular Schematics and the other without Angular Schematics.

Using Angular Schematics:

Below is the Angular CLI command to add the library to the Angular application. This will install Apollo Angular and associated libraries.

ng add apollo-angular

This single command will install the packages @apollo/client, apollo-angular, and graphql. This will also create the module graphql.module.ts and do the basic setup.

While the above command is executed, it will prompt to provide the GraphQL server endpoint, and it will configure the provided endpoint url in the “graphql.module.ts” file. Later we can change the endpoint as required.

GraphQL Client for Angular

Once the endpoint is provided, and the packages are installed, we can see the below graphql.module.ts file created with the necessary imports and endpoint we provided.

In the above screenshot, you can see that Link and Cache are configured in the create polls function.

Link controls the flow of data between Apollo Client and the GraphQL server. Chain of link objects can be assigned to the link parameter to customize the request and response. The HttpLink that is currently added connects the client to the external GraphQL Server. There are options to customize the behaviour of the link, however, only the endpoint is required to be added in the HttpLink options to make a simple request.

Cache stores the GraphQL query responses in the normalized in-memory cache. This enables the client to respond to future queries for the same data without sending further unwanted network requests. The cache is now configured with default options, and it is possible to customize by providing options objects to the InMemoryCache constructor.

Without Using Angular Schematics:

To do the installation manually, execute the below command, and it will install the required packages.

npm install apollo-angular @apollo/client graphql

Once the packages are installed, create the graphql.module.ts file similar to what was automatically generated by Angular schematics and import the module in app.module.ts.

The @apollo/client package requires AsyncIterable, so “esnext.asynciterable” needs to be added in the tsconfig.json compiler options below.

tsconfig.json compiler options

By following one of the above two methods, all the dependencies can be set up, and the application is ready to perform the first GraphqL request.

First GraphQL Request

The “Apollo” service is available, and we can use it to perform the request and pull the response data into the UI component.

The query string that needs to be sent in the request must be wrapped with the gql function to parse it into a standard GraphQL AST(Abstract Syntax Tree), then import it into the component using the snippet below:

import {Apollo, gql} from ‘apollo-angular’;

Below is a sample query wrapped with the gql function to retrieve the country list from a GraphQL server.

retrieve gql function from a GraphQL server.

The next step is to send the request to the server for a response. Apollo.watchQuery method has a query property to which pass our request. it. This method returns an object which changes the value of the property to an Observable. The response object will be passed through this Observable, containing loading, error, and data properties.

Apollo.watchQuery method

We have made our first query and got the response in the data property in the response object.

Mutations

Using the queries, we can get the data from the server. Now to update the data in the server, GraphQL mutations can be used.

Similar to query strings, mutation strings need to be created and wrapped inside the gql function. The mutation string consists of two parts:

  1. The mutation name with parameters, which indicates the actual operation to be done on the server.
  2. Which fields are to be returned from the server after the update.

Below is a sample mutation to update the country data.

gql function mutation string

Similar to the Apollo.watchQuery method that is used for querying data, Apollo. We can also use the Mutate method to call the mutation request. The mutation method returns an Observable, and we can subscribe to it and retrieve the returned data.

Mutate method to call the mutation request

Using Multiple Endpoints – GraphQL Client for Angular

So far, we have been using a single GraphQL client with a single endpoint. In some cases, there might be a need to use different GraphQL endpoints for different modules or to fetch data from some other servers. We can set up multiple named apollo clients in the application, pointing to different endpoints in such cases.

Few updates need to be made in the graphql.module.ts file. The create polls function needs to be updated to return the NamedOptions instead of ApolloCientOptions. Comments in the below image describe the updates to be done to use multiple endpoints.

GraphQL Client for Angular

To use the multiple clients created, Apollo.use method needs to be used per the example s below to select a particular named client, and then this.apolloCountries.watchQuery and this.apolloData.watchQuery methods to query the data from the respective server.

GraphQL Client for Angular

Adding Headers

The GraphQL server endpoints will not be public in most use cases, and the client must identify itself to the server. One common way is to send an authorization header in the request. Using middleware, it’s easy to add an Authorization header to every request.

Import ApolloLink, setContext, and update the createApollo function to send the headers. The ApolloLink library chains the function that adds the header, and the HTTP link creates a function. The request to the server will now be sent via the session token in the header.

GraphQL Client for Angular

GraphQL Client for Angular – Summary

In this article, we covered things like setting up the Apollo Angular GraphQL client and sending authentication queries/mutations to the server. Only the basic options were covered in this article however, there are many other options available in Apollo Angular for further exploration!

To know more about how the integration of Apollo Angular GraphQL can benefit your business, we encourage you to reach out and speak with us. We are sure that our solutions can help support your product development requirements and help you achieve your business goals.

Leave a Reply

Your email address will not be published. Required fields are marked *

8 + eighteen =