I have identified this task as utilizing Apollo Links within the vanilla Apollo Client.
Specifically, it involves creating a directional composition link chain.
https://i.sstatic.net/PQlx7.png
While my prototype may be verbose, the key points to focus on are:
- Using
ApolloLink.split
during ApolloClient initialization to direct queries to different endpoints.
- Implementing redirection in the
Apollo Link
using a boolean operation.
- In the example provided, I am utilizing "context" as part of query options.
It's worth noting that excessive complexity is not necessary.
Below is my prototype (NextJS + TypeScript + ApolloClient):
libs/apollo/index.ts
(where you define your apollo client)
import { ApolloClient, ApolloLink, HttpLink, InMemoryCache } from '@apollo/client'
// Define endpoints
const animeEndpoint = new HttpLink({
uri: 'https://graphql.anilist.co',
})
const countriesEndpoint = new HttpLink({
uri: 'https://countries.trevorblades.com/',
})
// Optional for type safety.
export enum Endpoint {
anime = 'anime',
country = 'country',
}
// Configure apollo-client with endpoints
const client = new ApolloClient({
// Custom property "Version" determines which endpoint to use
// Truthy = animeEndpoint (second) parameter, falsy = countriesEndpoint (third) parameter
link: ApolloLink.split((operation) => operation.getContext().version === Endpoint.anime, animeEndpoint, countriesEndpoint),
cache: new InMemoryCache(),
})
export default client
app/page.tsx
(for NextJS implementation)
'use client'
import { useQuery } from '@apollo/client'
import GetAnimeQuery from '@/libs/gql/GetAnime' // GraphQL query
import { Endpoint } from '@/libs/apollo'
import GetCountriesQuery from '@/libs/gql/GetCountries' // GraphQL query
export default function Home() {
// Fetch Anime data
const { loading: loadingAnime, error: errorAnime, data: dataAnime } = useQuery(GetAnimeQuery, { context: { version: Endpoint.anime } })
// Fetch Countries data
const {
loading: loadingCountries,
error: errorCountries,
data: dataCountries,
} = useQuery(GetCountriesQuery, { context: { version: Endpoint.country } })
console.log('Countries', dataCountries)
console.log('Anime', dataAnime)
return (
<main>
{loadingAnime && <p>Loading Anime...</p>}
{errorAnime && <p>Error Anime :{errorAnime.message}</p>}
{loadingCountries && <p>Loading Countries...</p>}
{errorCountries && <p>Error Countries:{errorCountries.message}</p>}
</main>
)
}
Appendix (skip unless requiring graphql queries)
libs/gql/GetAnime.ts
import { gql } from '@apollo/client'
const GetAnimeQuery = gql`
query Get {
Page(page: 1, perPage: 5) {
pageInfo {
total
currentPage
lastPage
hasNextPage
perPage
}
media {
id
title {
romaji
}
}
}
}
`
export default GetAnimeQuery
libs/gql/GetCountries.ts
import { gql } from '@apollo/client'
const GetCountriesQuery = gql`
query GetAllCountries {
countries {
code
currency
name
}
}
`
export default GetCountriesQuery