GQLoom

Federation

Apollo Federation allows you to declaratively combine multiple GraphQL APIs into a single federated graph. A federated graph enables clients to interact with multiple APIs through a single request.

GQLoom Federation provides GQLoom's support for Apollo Federation.

Installation

npm i graphql @gqloom/core @apollo/subgraph @gqloom/federation

GraphQL Directives

Apollo Federation directives (Directives) are used to describe how to combine multiple GraphQL APIs into a federated graph.

Declare Directives on Objects

In GQLoom, we can declare GraphQL directives in the directives field of the extensions property of objects and fields:

import * as  from "valibot"
import {  } from "@gqloom/valibot"
 
export const  = .(
  .({
    : .(),
    : .(),
  }),
  ({
    : "User",
    : {
      : { : { : "id", : true } },
    },
  })
)
 
export interface IUser extends .<typeof > {}

In the above example, we declared a @key directive, which marks the id field of the User object as a resolvable field. We will get the following Schema:

GraphQL Schema
type User
  @key(fields: "id", resolvable: true)
{
  id: String!
  name: String!
}

Declare Directives on Resolvers

We can also use resolvers to declare directives for objects:

export const userResolver = resolver
  .of(User, {
    // ...
  })
  .directives({ key: { fields: "id", resolvable: true } })

Add Directives to the Schema

const schema = FederatedSchemaLoom.weave(
  userResolver,
  FederatedSchemaLoom.config({
    extensions: {
      directives: {
        link: [
          {
            url: "https://specs.apollo.dev/federation/v2.6",
            import: ["@extends", "@external", "@key", "@shareable"],
          },
        ],
      },
    },
  })
)

Directive Formats

We have two formats for declaring directives:

  • Using an array:
{
  directives: [
    {
      name: "validation",
      args: {
        regex: "/abc+/"
      }
    },
    {
      name: "required",
      args: {},
    }
  ]
}
  • Using key-value pairs:
{
  directives: {
    validation: {
      regex: "/abc+/"
    },
    required: {}
  }
}

Resolve Reference

@gqloom/apollo provides the resolveReference function to help you resolve references.

import {  } from "@gqloom/core"
import { ,  } from "@gqloom/federation"
 
export const  = 
  .(, {
    : (, () => ({ : "1", : "John" })),
  })
  .({ : { : "id", : true } })
  .(() => (.))

Weaving

The FederatedSchemaWeaver.weave function imported from @gqloom/federation is used to weave the Federation Schema. Compared with @gqloom/core, the FederatedSchemaWeaver.weave function in @gqloom/apollo will output a Schema with directives.

It's also worth noting that we need to use the printSubgraphSchema function imported from @apollo/subgraph to convert the Schema to text format to preserve the directives.

import {  } from "@gqloom/federation"
import {  } from "@apollo/subgraph"
 
const  = .()
const  = ()

On this page