The basics of GraphQL and Apollo

Need Help in apollo-graphql

hi sir, I am Abhijeet from India. I just started working on graphql.I am trying to set reminder in apollo-graphql and I have no idea how it works in apollo. I am doing only backend graphql (nodejs) . help me for set a reminder in backend using apollo-graphql. This is urgent for me to create my new project.

hi sir, I am Abhijeet from India. I just started working on graphql.I am trying to set reminder in apollo-graphql and I have no idea how it works in apollo. I am doing only backend graphql (nodejs) . help me for set a reminder in backend using apollo-graphql. This is urgent for me to create my new project.

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 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.

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

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

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

How to use Apollo Server 2 and GraphQL

How to use Apollo Server 2 and GraphQL

Learn GraphQL, Apollo Server 2, and Black-box Testing. In this tutorial I will be showing you how to use Apollo Server 2 and GraphQL. Understanding of GraphQL by setting up your GraphQL schema that represents the structure of your data set, furthermore, we will do this by looking at TypeDefs (type definitions). We will be using Jest to test our data sources, and then we will be creating black-box tests (snapshots) to test our typedefs & resolvers -- which will be hooked up to fixture files (mock data).

In this video I will be showing you how to use Apollo Server 2 and GraphQL. You will gain an understanding of GraphQL by setting up your GraphQL schema that represents the structure of your data set, furthermore, we will do this by looking at TypeDefs (type definitions). Once we have created our schema the next step will be to let Apollo Server know how to interact with that schema, essentially how to execute queries. To do this we will use something called a resolver, a resolver essentially tells Apollo how to fetch data, moreover how to fetch data for a particular type. Once we have setup our resolvers we will look at data sources. Data sources are nothing more than a class that sets out our scaffolding for making requests to external APIs (in our case). Although we just touch the surface of what a data source can do by using RESTDataSource, they can do much more.

Towards the end of this video, we will be using Jest to test our data sources, and then we will be creating black-box tests (snapshots) to test our typedefs & resolvers -- which will be hooked up to fixture files (mock data). For a quick TLDR of what we have done, skip to 2:58:49 - I essentially went with the format of 'schema (typedefs) -- resolvers -- datasources'.

⏳ Timeline
0:00:00 - Reviewing where we left off
0:03:19 - Quick look over the UI of the first tutorial
0:03:30 - Github repo of the first project
0:04:06 - Reviewing the read me
0:04:21 - Initial setup for our application
0:04:36 - Creating our package.json file
0:07:01 - Optional chaining import!
0:09:46 - Installing all our packages
0:10:26 - Creating our server.js file
0:11:11 - Setting up ApolloServer
0:12:41 - Setting up our typedefs
0:12:51 - Setting up our resolvers
0:13:30 - Quick talk about how GraphQL handles field requests
0:15:47 - Similarities between GQL & RPC
0:18:07 - Adding typedefs within (typedefs/index.js)
0:19:02 - Creating our Article object type
0:20:22 - Defining an instance of an executable query
0:21:32 - Adding more fields to our Article object type
0:26:25 - Creating our essential .babelrc file
0:26:55 - Starting our server!
0:27:25 - Exploring Graphiql on port 4000
0:33:55 - Executing a dummy query
0:36:10 - Hooking up our resolvers
0:37:49 - Exploring resolver arguments
0:39:54 - Logging our executable query arguments
0:40:19 - Exploring the context argument
0:44:09 - Creating our datasource files
0:49:01 - Implementing the hackernews.js datasource
0:52:30 - Explaining RESTDataSource
1:00:01 - Adding methods to our datasource
1:03:36 - Adding a transformer method
1:05:06 - Adding our datasource to our index.js
1:06:01 - Accessing our datasource via the context argument
1:07:21 - Adding all datasources to the context
1:09:51 - Our first successful query via Graphiql!
1:10:56 - Adding more resolvers
1:13:22 - Adding more executable queries into our typedefs
1:15:12 - Debugging syntax errors
1:18:08 - Succesful query responses
1:23:08 - Async resolver explained
1:27:23 - Testing our allArticles resolver
1:31:23 - Adding the New York Times datasource
1:40:03 - Adding the fixture files for testing
1:43:23 - Testing the HackerNews datasource
2:02:03 - Looking at the Apollo documentation for testing
2:06:13 - Testing the HackerNews queries
2:28:48 - Running our black-box tests
2:40:32 - The difference in mocking return objects/arrays
2:43:38 - Checking our coverage levels
2:45:05 - Testing the New York Times datasource
2:49:00 - Testing the New York Times queries
2:52:25 - Checking coverage, nearly at 100%
2:55:15 - 100% test coverage (unit & black-box tests)
2:55:50 - Quick look at aliases
2:58:49 - TLDR: overview of the project!
3:08:00 - Signing off!