Tutorial To Apollo GraphQL Federation for Beginners

Tutorial To Apollo GraphQL Federation for Beginners

In this article, we will see what is Apollo Federation and what kind of problem that federation is trying to solve with a real-time example. Introduction to Apollo GraphQL Federation

If you are a beginner in GraphQL, I recommend you to learn the basics of GraphQL from something like this course.

Apollo Federation is an architecture of composing multiple GraphQL services into a single endpoint.

when you start to think about building a microservice, it would be difficult to divide the GraphQL layer for different services. For example, we are dividing it something like this – This is image title This may seem to make sense at first. but, the problem is adding a new feature. Let’s say that we want to add top comments in Post. Post-service doesn’t know how to resolve a query for top comments because data about comment will be stored in the Comment Service.

On the other hand, Apollo Federation allows us to extend the Post type in Any Service, Here Comment service with a extend type functionality. This is image title Therefore, this keeps all the code for a given feature in a single service and separated from unrelated concerns.

complete source code can be found here

Federation Core Concepts

Mainly, let us see the core concept of apollo federation which compiles different services together to form a single graph

Entities and keys

Firstly, It is a type which is referenced by another service. it creates a connection between services and form a federated graph. entities have a primary key which identifies the specific instance of the type.

entities can be declared by using a keyword @key in the Type

type User @key(fields: "_id") {
   _id : ID
   name : String
   email : String
}

External Type Reference

Once, the entity is declared, other services can reference this type from their own types. Let’s see how the Comment Service refer the User Service in our example

type Comment {
   user: User
}

extend type User @key(fields : "_id") {
   _id : ID @external
}

Likewise, In this example, we have Comment type with a field called user that return the User type. Since User is an entity that lives in another service, we define that type in this service with just enough information to enable composition.

  • extend keyword declares the User is an entity defined elsewhere, here it is User Service
  • The @Key declares the ‘name’. We will use _id to refer to a particular user.
  • The _id field with an @external directive declares the type of _id field(ID ) that is implemented in another service.

On the other hand, To get all the values of Referenced User in Comment Type Definition. we need to write some logic in the Resolver.

Comment: {
        user(comment) {
            return { __typename: "User",_id : comment.userId }
        }
    },
{ __typename: "User",_id : comment.userId }

object is a representation of a User entity. Representations are how services reference each other’s types.

As a result, the gateway will use the representation as an input to the service that owns the referenced entity. So to allow the gateway to get all the values in the referenced service. we need to reference resolver back in the User service.

User: {
        async __resolveReference(object) {
            return await UserModel.getUserById(object._id);
        }
    }

Now, we could get user details in the Comment Type using the reference of it which is a UserID

This is image title

Extending external types

However, Extending external types solves the problem of one to many relationship use-cases. For example, Post can have many comments and a comment belongs to a post. In the previous section, we just saw external type reference. Here we will see Extending external type

For example, we want to add comments field to Post type

extend type Post @key(fields: "_id"){
        _id : ID @external
        comments : [ Comment! ]
    }

we can extend the Post type in the Comment service and extend the type with comments which are the type of Comment

Since the Comment service already had a concept of the Post type from returning it, adding additional fields to the overall type can be done just like it was a normal type.

query plan will fetch the _id field for each Post from the Post service and pass those to the comment service, where you can then access these fields on the object passed into your comments

resolver:

Post: {
        comments(post) {
            return CommentModel.getCommentByPost(post._id);
        }
    }

Building Microservice

complete source code can be found here

Let us build a blog application using apollo federation. it contains three services and an API gateway This is image title You can get the source code for each of the services below –

User Service Post Service Comment Service

API Gateway

Firstly, we will create a gateway which connects all the services with a single GraphQL endpoint.

Initialize the project and create a file called gateway.js

npm init --yes
npm install @apollo/gateway apollo-server graphql

touch gateway.js

After that, add the following code in gateway.js

const { ApolloServer } = require('apollo-server');

const { ApolloGateway } = require('@apollo/gateway');

const gateway = new ApolloGateway({
    serviceList: [
      { name: "users", url: "http://localhost:4001/graphql" },
      { name: "posts", url: "http://localhost:4002/graphql" },
      { name: "comments", url: "http://localhost:4003/graphql" },
      // { name: "inventory", url: "http://localhost:4004/graphql" }
    ]
  });

  (async () => {
    const { schema, executor } = await gateway.load();

    const server = new ApolloServer({ schema, executor });

    server.listen().then(({ url }) => {
      console.log(` Server ready at ${url}`);
    });
  })();

we provide serviceList configuration to the Apollo gateway which provides the name and endpoint for each federated services. name is used for error messages and logging.

API Gateway – Authentication Across services

In Microservice architecture, it is important to authenticate request across different services. This blog explains Microservices Authentication in detail. To achieve this, Apollo Gateway shares the context across services.

@apollo/gateway makes it easy to reuse the context feature of Apollo to customize what information is sent to underlying services.

const { ApolloServer } = require('apollo-server');
const { ApolloGateway, RemoteGraphQLDataSource } = require('@apollo/gateway');

const gateway = new ApolloGateway({
  serviceList: [
     { name: "users", url: "http://localhost:4001/graphql" },
      { name: "posts", url: "http://localhost:4002/graphql" },
      { name: "comments", url: "http://localhost:4003/graphql" },
    // other services
  ],

  buildService({ name, url }) {
    return new RemoteGraphQLDataSource({
      url,
      willSendRequest({ request, context }) {
        // pass the user's id from the context to underlying services
        // as a header called `user-id`
        request.http.headers.set('x-user-id', context.userId);
      },
    });
  },
});

const server = new ApolloServer({
  gateway,

  context: ({ req }) => {
    // get the user token from the headers
    const token = req.headers.authorization || '';

    // try to retrieve a user with the token
    const userId = getUserId(token);

    // add the user to the context
    return { userId };
  },
});

server.listen().then(({ url }) => {
  console.log(` Server ready at ${url}`);
});

In this example, buildService return a custom RemoteGraphQLDataSource which allow us to modify the outgoing request with information from the Apollo Service context .request from gateway send x-user-id in the request header across services.

Moreover, To Learn more about buildService or RemoteGraphQLDataSource, read the API Docs

Summary

To sum up, we can build a Microservices using apollo federation which solves the problem of stitching GraphQL to a single endpoint. Several teams can work in different services without any dependency between services.

Originally published by Ganeshmani P at codewall.co.uk

graphql apollo web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.