graffle-js / graffle

Simple GraphQL Client for JavaScript. Minimal. Extensible. Type Safe. Runs everywhere.
http://graffle.js.org/
MIT License
5.99k stars 311 forks source link

Bug in middleware docs #1349

Open giaset opened 3 weeks ago

giaset commented 3 weeks ago

Perceived Problem

The middleware docs (https://github.com/graffle-js/graffle/blob/graphql-request/examples/other-middleware.ts) propose that we do the following if we want to add a custom header

const requestMiddleware: RequestMiddleware = async (request) => {
    return {
      ...request,
      headers: {
        ...request.headers,
        'x-auth-token': await getAccessToken(),
      },
    }
  }

However, in my case, request.headers is a HeadersInit object and it didn't seem like the spread operator was working correctly over that object (as a concrete example, I no longer had Content-Type: application/json going out on my requests...)

Ideas / Proposed Solution(s)

I was able to fix the issue by doing the following:

requestMiddleware: async request => {
    const oldHeaders = Object.fromEntries(request.headers?.entries());

    return {
      ...request,
      headers: {
        ...oldHeaders,
        'x-auth-token': await getAccessToken()
      }
    };
  }

It seems like the spread operator works just fine over this oldHeaders object and all the expected headers now show up in my requests (Content-Type: application/json, etc)

jasonkuhrt commented 3 weeks ago

Yep you're right, this is fixed in some places but looks like I didn't catch this case. Will fix, PR welcome.