Table of Contents
Excessive data fetching has always been a point of concern for the app developers, and are in a lookout for a solution that can fetch the right amount of data. GraphQL – a revolutionary query language for web API, is one such contribution made by Facebook. GraphQL has come out as a game-changer in the application development process, enhancing the communication between front-end as well as the back-end of the application.
Being strongly typed, fast, self-documented as well as dissociated with the storage, GraphQL empowers the developers to include it at any stage of the app development process, without interrupting the existing database. The simplicity of GraphQL, making it more comprehensible as well as easy to learn, is also one of the major reasons which have made it the choice of many tech pioneers like Facebook, Shopify, StackShare, Twitter, etc.. Unlike other query languages, GraphQL does not use the complicated text string instead utilizes the object structure to manage data.
For Example,
If you want to fetch the details of a book from the database. The SQL query for the action will be like:
SELECT name, author, genre, price FROM books
To write it in the GraphQL, the query seems more understandable, written the same as the structure of the object.
{
Book{
batch_no.
name
author
genre
price
}
}
However, the challenges do not end with the data fetching – front end, back end and cache data management are also important. A client can help you here, allowing you to execute the API on it and track its performance. Among the various available clients, Apollo, with an interpretative data fetching approach and smart caching, proves to be one of the best clients used for API development.
Considering its efficacies, pairing Apollo with the GraphQL comes out as an extremely productive combination. This combination expedites the development process, empowering the developers to add or remove fields in the API directly, instead of writing a huge amount of boilerplate code. Apollo works for various JavaScript platforms such as Angular, React, etc. for App development. Let’s take up Angular and check out how it works on GraphQL and Apollo.
How to work with GraphQL and Apollo in Angular?
Apollo liberates the applications from finding ways to load data, managing everything at its end. User Interface requests the data through GraphQL, and then Apollo manages the rest by fetching, caching, and availing the data to the API. Let’s check out the steps to create an Angular application using Apollo and GraphQL.
-
- The first and foremost step is to install the Angular Command Line Interface and then set up the GraphQL server or
Launch it from the Apollo Launchpad.
import { makeExecutableSchema } from 'graphql-tools';
const typeDefs = `
type Query {
allBooks: [Book]
book(batch no.: Int!): Book
},
type Book {
batch_no.: Int
name: String
author: String
genre: String
price: Int
};
var coursesData = [
{
batch_no.: 1,
name: 'The Complete Book of C++',
author: 'Herbert Schildt',
genre: programming
price: 6.57 USD
},
{
batch_no.: 2,
name: 'Learning Python',
author: 'Mark Lutz',
genre: programming
price: 8.17 USD
},
{
batch_no.: 3,
name: 'Java in a Nutshell',
author: 'David Flanagan',
genre: programming
price: 7.57 USD
}
];
var getBook = function(root, {batch no.}) {
return BooksData.filter(Book => {
return Book.batch_no. === batch_no.;
})[0];
};
var getAllBooks = function() {
return BooksData;
}
const resolvers = {
Query: {
allBooks: getAllBooks,
Book: getBook,
},
};
export const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
-
- Create an Angular project.
- After creating the project, add Angular Apollo Client with the command:
ng add apollo-angular
-
- Once the command is executed, import the following dependencies such as-
- Angular Ng Module
- App Component
- Apollo Module
- Graphql-tag
- HttpClientModule
- Apollo-angular-link-http
- InMemoryCache
- Add the address of your GraphQL server within the GraphQL module file.
- Once the command is executed, import the following dependencies such as-
const uri = '.... URL of GraphQL server...';
-
- Update the constructor with a link and cache-
- Link: Link creates a HttpLink() method, which connects to the GraphQL server.
- Update the constructor with a link and cache-
link: httpLink.create({uri: '[URL]'})
-
-
- Cache: Cache creates an instance of InMemoryCache(), which can be used to store data for API.
-
cache: new InMemoryCache()
When an object is created, the constructor creates a network connection with the GraphQL server.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ApolloModule, Apollo } from 'apollo-angular';
import { HttpClientModule } from '@angular/common/http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { AppComponent } from './app.component';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
ApolloModule,
HttpLinkModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
constructor(apollo: Apollo, httpLink: HttpLink) {
apollo.create({
link: httpLink.create({uri: '[URL]'}),
cache: new InMemoryCache()
});
}
}
-
- Once you have set up the Apollo client and established the connection, import the necessary components required in your application such as CSS file, HTML file, type definition, etc., you can retrieve data and provide it to the user.
Code for Type definition-
export type Book= {
batch_no.;
name: string;
author: string;
genre: string;
price: number;
}
export type Query = {
allBooks: Book[];
}
-
- To retrieve the details of Books from the GraphQL through Apollo Client, you can use the following code:
export class ListComponent implements OnInit {
Books: Observable<Book[]>;
constructor(private apollo: Apollo) { }
ngOnInit() {
this.Books = this.apollo.watchQuery({ //watchQuery eecutes the query
query: gql`
query allBooks {
allBooks {
batch_no.
name
author
genre
price
} } `
})
.valueChanges
.pipe(
map(result => result.data.allBooks)
);
}
}
Now, you can modify the HTML code of your Angular App and link the Apollo client in the code. Execute the code and check out the result in the browser.
Take-Away
GraphQL is the modern way of interacting with the database and Apollo Client makes the interaction even better, providing a perfect environment to execute the API seamlessly, by fetching and storing API data at its end. GraphQL is packed with various unique features:
- A Declarative approach of fetching data from the server.
- Handles complex networking activities at its end.
- Liberates you from making multiple HTTP requests for data.
- Works on the tight coupling of data dependencies and the view layer of the application, enabling you to control the User Interface code and the data in parallel.
Apollo Client, on the other hand, not only handles the responses generated by the GraphQL server but also caches them for future references. Some highlighting features that make it a perfect fit for GraphQL and JavaScript applications.
- Incrementally adaptable at any stage of the app development.
- Easy to use and understand.
- Smaller in size.
- Community-driven.
By now, you might have understood the importance of GraphQL and Apollo in the Application development process and how to incorporate it into your project. However, if still on the fence, reach out to us and get your queries resolved. Or Hire an Angular developer and handover your hassle to us.