Skip to content

Commit

Permalink
fix: Don't crash when receiving non-string, non-array headers (#197)
Browse files Browse the repository at this point in the history
  • Loading branch information
AaronMoat authored May 1, 2023
1 parent caf01fb commit fcd05fa
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/polite-trainers-camp.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@apollo/datasource-rest': patch
---

Don't crash when receiving non-string, non-array headers
12 changes: 6 additions & 6 deletions src/HTTPCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,12 +331,12 @@ function cachePolicyHeadersToNodeFetchHeadersInit(
): NodeFetchHeadersInit {
const headerList = [];
for (const [name, value] of Object.entries(headers)) {
if (typeof value === 'string') {
headerList.push([name, value]);
} else if (value) {
if (Array.isArray(value)) {
for (const subValue of value) {
headerList.push([name, subValue]);
}
} else if (value) {
headerList.push([name, value]);
}
}
return headerList;
Expand All @@ -354,10 +354,10 @@ function cachePolicyHeadersToFetcherHeadersInit(
): Record<string, string> {
const headerRecord = Object.create(null);
for (const [name, value] of Object.entries(headers)) {
if (typeof value === 'string') {
headerRecord[name] = value;
} else if (value) {
if (Array.isArray(value)) {
headerRecord[name] = value.join(', ');
} else if (value) {
headerRecord[name] = value;
}
}
return headerRecord;
Expand Down
29 changes: 29 additions & 0 deletions src/__tests__/RESTDataSource.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1848,6 +1848,35 @@ describe('RESTDataSource', () => {
await dataSource.getFoo(2, true);
});

it('should not crash in revalidation flow header handling when sending non-array non-string headers', async () => {
jest.useFakeTimers({ doNotFake: ['nextTick'] });

const dataSource = new (class extends RESTDataSource {
override baseURL = apiUrl;

getFoo(id: number) {
return this.fetch(`foo/${id}`, {
headers: {
// @ts-expect-error
x: 1,
},
cacheOptions: { ttl: 1 },
});
}
})();

nock(apiUrl).get('/foo/1').times(2).reply(200);

await dataSource.getFoo(1);
await dataSource.getFoo(1);

jest.advanceTimersByTime(1000);

await dataSource.getFoo(1);

jest.useRealTimers();
});

describe('raw header access when using node-fetch', () => {
it('for a non-cacheable request', async () => {
const dataSource = new (class extends RESTDataSource {
Expand Down

0 comments on commit fcd05fa

Please sign in to comment.