Next API Fetcher

@natu/next-api-fetcher

GraphQL fetcher

This package exposes GraphQL-focused fetcher that can be used to easily retrieve data from GraphQL API.

ℹ️

Fetcher was used in storyblok-api package.

Usage

To use this package in the app import this package as a dependency in its individual package.json file:

"dependencies": {
  "@natu/next-api-fetcher": "*",
}

Then use it like in the example below:

getStoryblokData.ts
import { ApiFetcher } from '@natu/next-api-fetcher';
import { print } from 'graphql/language/printer';
 
const GetContentNode = gql`
  query getContentNode($slug: ID!, $relations: String = "", $skipContent: Boolean = false) {
    ContentNode(id: $slug, resolve_relations: $relations) {
      id
      first_published_at
      full_slug
      name
      published_at
      slug
      uuid
      content @skip(if: $skipContent)
    }
  }
`;
 
const { fetcher } = new ApiFetcher(GRAPHQL_ENDPOINT, {
  headers: { ...headers },
  cache: 'force-cache',
});
 
const { data } = await fetcher<VariablesType, DataType>({
  query: print(GetContentNode),
  { slug: 'web/home', relations: 'config.footer,config.header' },
  version: 'draft',
});
 
return data;

API Reference

ApiFetcher class

PropTypeDefaultDescription
endpointstring-GraphQL endpoint like https://gapi.storyblok.com/v1/api
requestParamsPick<RequestInit, 'headers | 'cache' | 'next'>{ headers: { 'Content-Type': 'application/json' } }headers and cache params known from the Fetch API ↗ (opens in a new tab) and the custom next param added by Next.js ↗ (opens in a new tab)

fetcher() method

PropTypeDefaultDescription
querystring-GraphQL query
cache"default" | "force-cache" | "no-cache" | "no-store" | "only-if-cached" | "reload"-Caching strategy
variablesExact<T>-Variables passed to GraphQL query
headersHeadersInit{ 'Content-Type': 'application/json' }HTTP headers
next{revalidate?: number | false; tags?: string[] }-Next param added by Next.js ↗ (opens in a new tab)