0.0.6 • Published 1 year ago

@calebbarnes/connect-client v0.0.6

Weekly downloads
-
License
ISC
Repository
-
Last release
1 year ago

connect-client

Use the Netlify Connect client to make GraphQL requests to your Data layer. This client automatically generates cache tags for any retrieved data from your Data Layer, enabling efficient caching of dynamic content on Netlify's CDN. When new data is published through your CMS, Netlify Connect sends a request to your site, containing the cache tags. These cache tags can be used to purge Netlify's CDN for any stale content.

The Netlify Connect client offers TypeScript type system support enhanced by gql.tada. This integration provides valuable editor feedback, auto-completion, and type hints.

Requirements

  • Site must be deployed to Netlify prior to starting
  • Install the GraphQL: Syntax Highlighting VSCode extension, for better GraphQL highlighting.

How to setup the Netlify connect client

  1. Install the client npm install @netlify/connect-client

  2. Generate required files for typescript support. The following command requires two environment variables to be passed:

DATA_LAYER_API_TOKEN=<API token> DATA_LAYER_API_URL=<API URL> npx @netlify/connect-client connect-generate

This will create a netlify-connect directory within the src director which will have four files:

  • connect-schema.graphql: Your Data Layer's GraphQL schema.
  • graphql-env.d.ts: Typescript types generated by the GraphQL schema.
  • tsconfig.ts: Used to create the graphql-env.d.ts.
  • graphql.ts: Exports graphql function to access types within your project.
  1. Update typescript configuration.
{
  "compilerOptions": {
    "plugins": [
      {
        "name": "@0no-co/graphqlsp",
        "schema": "src/netlify-connect/connect-schema.graphql"
      }
    ]
  }
}
  • The @0no-co/graphqlsp plugin is a TypeScript language server plugin to provide editor hints, diagnostics or errors when writing GraphQL documents
  1. VSCode settings Update the vscode settings to use the workspace version of typescript
{
  "typescript.tsdk": "node_modules/typescript/lib",
  "typescript.enablePromptUseWorkspaceTsdk": true
}

Setup Netlify function

Make sure you have the @netlify/functions installed in your project. Then add the following netlify function:

import { purgeCache } from "@netlify/functions";

export default async (req: Request) => {
  const body = await req.json();

  console.log(body);

  if (!body?.cacheTags?.length) {
    return new Response("No tags to purge", { status: 400 });
  }

  try {
    await purgeCache({
      tags: body.cacheTags,
    });
  } catch (error) {
    console.error(error);
  }
  
  return new Response("Purged!", { status: 202 });
};

export const config = {
  path: "/connect-purge",
};

For Next.js you will need to add a connect-purge api route:

import { revalidateTag } from "next/cache";
import { NextRequest, NextResponse } from "next/server";

export async function POST(req: NextRequest) {
  const body = await req.json();

  console.log(body);

  if (body.cacheTags?.length) {
    try {
      body.cacheTags.forEach((tag: string) => {
        return revalidateTag(tag);
      });
    } catch (e) {
      console.error(e);
    }
  }

  return NextResponse.json({ success: true }, { status: 200 });
}

Setup Netlify Connect

Create a custom webhook for your Data Layer with the prefix invalidation_hook_. When a data update is performed, Netlify Connect will send a webhook to invalidate any pages that have been updated. Add your sites URL with a /connect-purge route. Example: https://invalidation_hook_my-awesome-site/connect-purge

How to use the connect-client

Make sure to add the following environment variables to your Netlify Site:

  • DATA_LAYER_API_TOKEN: A GraphQL API token for your Data layer.
  • DATA_LAYER_API_URL: Your Data Layer's GraphQL API URL.

From your project you can import graphql from netlify-connect/graphql and start writing GraphQL queries with type support.

To make a request to your api import query from @netlify/connect-client

With Astro you need to pass in the Global Astro object to set the correct headers to purge the Netlify CDN cache when a data update is performed:

import { query } from "@netlify/connect-client";
import { graphql } from "../netlify-connect/graphql"; <-- Relative path

const booksQuery = graphql(`
  query books {
    allContentfulBook {
      nodes {
        id: contentful_id
        title
        coverImage {
          url
        }
        author {
          name
        }
      }
    }
  }
`);

export const getBooks = async (Astro: any) => {
  const res = await query(booksQuery, { Astro });
  return res.allContentfulBook.nodes;
};

With Next.js you can make the request without any additional options.

Options

The query function can be passed additional options:

  • endpointOverride the Data Layer API url.
  • token Override the Data Layer API token. This is used for making requests to your Data Layer with a permission scoped API token.
  • Astro Global Astro object. If you are using the Astro framework, you must pass the Global Astro Object to add the correct cache tags on the Response.

How it works

When a request is made to fetch dynamic content from your site, the Netlify client will add cache-tags to the Response object before it is served to the client. This will allow the content to be cached on Netlify's CDN.

These cache tags can be passed on to purge any stale content on Netlify's CDN with Netlify's purge cache api.

0.1.0-beta.0

1 year ago

0.0.6

1 year ago

0.0.5

1 year ago

0.0.4

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago