Skip to content

Commit

Permalink
refactor: simplify graphqlFetch by unsupporting RequestInfo and `Re…
Browse files Browse the repository at this point in the history
…questInit`
  • Loading branch information
angeloashmore authored and lihbr committed Jan 6, 2022
1 parent 9b5a126 commit 580c4d5
Showing 1 changed file with 26 additions and 20 deletions.
46 changes: 26 additions & 20 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1270,29 +1270,35 @@ export class Client {
const cachedRepository = await this.getCachedRepository();
const ref = await this.getResolvedRefString();

const url = typeof input === "object" ? input.url : input;
const headers = new Headers(init?.headers);
const unsanitizedHeaders: Record<string, string> = {
"Prismic-ref": ref,
"Prismic-integration-field-ref":
cachedRepository.integrationFieldsRef || "",
Authorization: this.accessToken ? `Token ${this.accessToken}` : "",
// Asserting `init.headers` is a Record since popular GraphQL
// libraries pass this as a Record. Header objects as input
// are unsupported.
...(init ? (init.headers as Record<string, string>) : {}),
};

if (!headers.has("Prismic-ref")) {
headers.set("Prismic-ref", ref);
}
if (
!headers.has("Prismic-integration-field-ref") &&
cachedRepository.integrationFieldsRef
) {
headers.set(
"Prismic-integration-field-ref",
cachedRepository.integrationFieldsRef,
);
}
if (!headers.has("Authorization") && this.accessToken) {
headers.set("Authorization", `Token ${this.accessToken}`);
const headers: Record<string, string> = {};
for (const key in unsanitizedHeaders) {
if (unsanitizedHeaders[key]) {
headers[key.toLowerCase()] =
unsanitizedHeaders[key as keyof typeof unsanitizedHeaders];
}
}

return (await this.fetchFn(url, {
...init,
headers: Object.fromEntries(headers),
})) as Response;
return (await this.fetchFn(
// Asserting `input` is a string since popular GraphQL
// libraries pass this as a string. Request objects as
// input are unsupported.
input as string,
{
...init,
headers,
},
)) as Response;
}

/**
Expand Down

0 comments on commit 580c4d5

Please sign in to comment.