Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(graphql): add graphql request helper #50

Draft
wants to merge 17 commits into
base: main
Choose a base branch
from

Conversation

matthew-gordon
Copy link
Collaborator

@matthew-gordon matthew-gordon commented May 2, 2024

Purpose

  • this adds a convenience method to wrap next's overriden fetch and make using the contentful graphql api/surface more manageable

example usage:

// lib/contentful/client.ts

import { createFetch } from "@contentful/vercel-nextjs-toolkit/graphql";

export const { fetchGraphQL } = createFetch({
  spaceId: process.env.CONTENTFUL_SPACE_ID!,
  accessToken: process.env.CONTENTFUL_ACCESS_TOKEN!,
  previewToken: process.env.CONTENTFUL_PREVIEW_ACCESS_TOKEN!,
});
// lib/contentful/api.ts

const POST_FIELDS_FRAGMENT = `#graphql
  fragment PostFields on Post {
    __typename
    sys {
      id
    }
    title
    slug
    author {
      name
    }
    coverImage {
      url
    }
    excerpt
    content {
      json
      links {
        assets {
          block {
            sys {
              id
            }
            url
            description
          }
        }
      }
    }
  } 
`;

const GET_ALL_POSTS_QUERY = `#graphql
  query GetPostQuery($where: PostFilter, $limit: Int, $preview: Boolean) {
    postCollection(where: $where, limit: $limit, preview: $preview) {
      items {
        ...PostFields
      }
    }
  }
  ${POST_FIELDS_FRAGMENT}
`;

export async function getAllBlogs(limit = 10) {
  const res = await fetchGraphQL({
     query: GET_ALL_POSTS_QUERY,
     variables:  {
       where: { 
         slug_exists: true 
       },
       limit,
       order: "slug_DESC",
     },
     revalidate: 5,
  });
 
  return res?.data?.postCollection?.items;
}

@matthew-gordon matthew-gordon force-pushed the mjg/feat/add-graphql-request-helper branch from 1b6af9e to 718f649 Compare May 6, 2024 19:20
@matthew-gordon matthew-gordon force-pushed the mjg/feat/add-graphql-request-helper branch from 3473141 to 2b7f88f Compare May 20, 2024 19:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant