Skip to content

Quramy/apollo-link-fragment-argument

Repository files navigation

apollo-link-fragment-argument

npm

An Apollo Link to enable@argumentDefinitions and @arguments directives inspired from Relay Modern's Fragment container.

Usage

Install

$ npm i apollo-link-fragment-argument

Configure apollo client

import { ApolloClient } from "apollo-client";
import { InMemoryCache } from "apollo-cache-inmemory";
import { from } from "apollo-link";
import { createHttpLink } from "apollo-link-http";

import { createFragmentArgumentLink } from "apollo-link-fragment-argument";

function createApolloClient() {
  const cache = new InMemoryCache();
  const link = from([
    createFragmentArgumentLink(),
    createHttpLink({
      uri: "http://your.graphql.endpoint",
    }),
  ]);
  return new ApolloClient({
    cache,
    link,
  });
}

Using @argumentDefinitions and @arguments directive in your query

const todoListFragment = gql`
  fragment TodoList_list on TodoList
    @argumentDefinitions(
      count: { type: "Int", defaultValue: 10 } # Optional argument
      userID: { type: "ID" } # Required argument
    ) {
    title
    todoItems(userID: $userID, first: $count) {
      # Use fragment arguments here as variables
      ...TodoItem_item
    }
  }
`;
const query = gql`
  query TodoListQuery($count: Int, $userID: ID) {
    ...TodoList_list @arguments(count: $count, userID: $userID) # Pass arguments here
  }
  ${todoListFragment}
`;

Why?

I'm loving GraphQL's fragments colocation.

combined with GraphQL's support for fragments, allows you to split your queries up in such a way that the various fields fetched by the queries are located right alongside the code that uses the field.

However, GraphQL syntax has no ability to parameterize Fragment (See graphql/graphql-spec#204 if you want detail).

@argumentDefinitions and @arguments are originally introduced by Relay Modern to compose parametrized Fragments. See https://relay.dev/docs/en/fragment-container.html#composing-fragments ,

License

MIT

About

An Apollo Link to enable to parameterize fragments

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published