jasonkuhrt / graphql-request

Minimal GraphQL client

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Memoizing fetch error: Body is unusable

MangoMarcus opened this issue · comments

Description

I've tried to memoize the fetch function for graphql-request using lodash.memoize, but it gives "Error: Body is unusable". Is this a bug or am I missing something?

Thanks

Reproduction Steps/Repo Link

import { GraphQLClient } from 'graphql-request';
import memoize from 'lodash/memoize';

export const gqlClient = new GraphQLClient(GRAPHQL_URL, {
  fetch: memoize(
    fetch,
    (...args) => JSON.stringify(args)
  ),
});

Screenshot

Screenshot 2024-04-25 at 13 02 03

For reference the gqlSdk in the screenshot is generated by graphql-codegen using import { getSdk, type SdkFunctionWrapper } from '@/generated/gql/sdk'; export const gqlSdk = getSdk(gqlClient);, it's just a simple wrapper around gqlClient.request though so the effect should be the same:

Screenshot 2024-04-25 at 13 08 28

Workaround

I've worked around the issue for now by memoizing the individual methods in that sdk instead of the underlying fetch

const unmemoizedGqlSdk = getSdk(gqlClient);
export const gqlSdk = Object.fromEntries(
  Object.entries(unmemoizedGqlSdk).map(([key, value]) => [
    key,
    memoize(value, (...args) => JSON.stringify(args)),
  ]),
);