Skip to content

Commit

Permalink
fix: make sure .fetch() supports Request instances
Browse files Browse the repository at this point in the history
  • Loading branch information
pheekus committed Apr 6, 2021
1 parent 790b981 commit 7f3c58c
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 14 deletions.
12 changes: 6 additions & 6 deletions src/backend/API.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as Core from '../core/index.js';

import { Headers, fetch } from 'cross-fetch';
import { Headers, Request, fetch } from 'cross-fetch';
import { storageV8N, v8n } from '../core/v8n.js';

import type { Graph } from './Graph';
Expand Down Expand Up @@ -128,8 +128,9 @@ export class API extends Core.API<Graph> {
this.version = params.version ?? API.VERSION;
}

private async __fetch(input: RequestInfo, init?: RequestInit): Promise<Response> {
private async __fetch(info: RequestInfo, init?: RequestInit): Promise<Response> {
let token = JSON.parse(this.storage.getItem(API.ACCESS_TOKEN) ?? 'null') as StoredToken | null;
const request = typeof info === 'string' ? new Request(info, init) : info;

if (token !== null) {
const expiresAt = new Date(token.date_created).getTime() + token.expires_in * 1000;
Expand All @@ -155,15 +156,14 @@ export class API extends Core.API<Graph> {
}
}

const headers = new Headers(init?.headers);
const headers = request.headers;
const method = init?.method?.toUpperCase() ?? 'GET';
const url = typeof input === 'string' ? input : input.url;

if (!headers.get('Authorization') && token) headers.set('Authorization', `Bearer ${token.access_token}`);
if (!headers.get('Content-Type')) headers.set('Content-Type', 'application/json');
if (!headers.get('FOXY-API-VERSION')) headers.set('FOXY-API-VERSION', this.version);

this.console.trace(`${method} ${url}`);
return fetch(input, { ...init, headers });
this.console.trace(`${method} ${request.url}`);
return fetch(request);
}
}
2 changes: 1 addition & 1 deletion src/customer/API.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export class API extends Core.API<Graph> {

private async __fetch(input: RequestInfo, init?: RequestInit): Promise<Response> {
let session = JSON.parse(this.storage.getItem(API.SESSION) ?? 'null') as StoredSession | null;
const request = new Request(input, init);
const request = typeof input === 'string' ? new Request(input, init) : input;

if (session !== null) {
const expiresAt = new Date(session.date_created).getTime() + session.expires_in * 1000;
Expand Down
29 changes: 22 additions & 7 deletions tests/backend/API.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ describe('Backend', () => {
await api.fetch(url);

const headers = new Headers({ ...commonHeaders, Authorization: `Bearer ${sampleToken.access_token}` });
expect(fetchMock).toHaveBeenCalledWith(url, { headers });
expect(fetchMock).toHaveBeenCalledWith(new Request(url, { headers }));

fetchMock.mockClear();
});
Expand All @@ -248,7 +248,7 @@ describe('Backend', () => {
});

const headers = new Headers({ ...commonHeaders, Authorization: `Bearer ${sampleToken.access_token}` });
expect(fetchMock).toHaveBeenNthCalledWith(2, url, { headers });
expect(fetchMock).toHaveBeenNthCalledWith(2, new Request(url, { headers }));

fetchMock.mockClear();
});
Expand All @@ -272,7 +272,7 @@ describe('Backend', () => {
});

const headers = new Headers({ ...commonHeaders, Authorization: `Bearer ${sampleToken.access_token}` });
expect(fetchMock).toHaveBeenNthCalledWith(2, url, { headers });
expect(fetchMock).toHaveBeenNthCalledWith(2, new Request(url, { headers }));

fetchMock.mockClear();
});
Expand All @@ -295,22 +295,37 @@ describe('Backend', () => {
method: 'POST',
});

expect(fetchMock).toHaveBeenNthCalledWith(2, url, { headers: new Headers(commonHeaders) });
expect(fetchMock).toHaveBeenNthCalledWith(2, new Request(url, { headers: commonHeaders }));

fetchMock.mockClear();
});

it('supports complex fetch requests', async () => {
it('supports complex fetch requests with detailed arguments', async () => {
fetchMock.mockImplementation(() => Promise.resolve(new Response(null, { status: 500 })));

const api = new BackendAPI(commonInit);
const info = new Request(BackendAPI.BASE_URL.toString());
const info = BackendAPI.BASE_URL.toString();
const init = { headers: { foo: 'bar' }, method: 'POST' };

await api.fetch(info, init);

const headers = new Headers({ ...commonHeaders, ...init.headers });
expect(fetchMock).toHaveBeenLastCalledWith(info, { ...init, headers });
expect(fetchMock).toHaveBeenLastCalledWith(new Request(info, { ...init, headers }));

fetchMock.mockClear();
});

it('supports complex fetch requests with Request instances', async () => {
fetchMock.mockImplementation(() => Promise.resolve(new Response(null, { status: 500 })));

const api = new BackendAPI(commonInit);
const info = BackendAPI.BASE_URL.toString();
const init = { headers: { foo: 'bar' }, method: 'POST' };

await api.fetch(new Request(info, init));

const headers = new Headers({ ...commonHeaders, ...init.headers });
expect(fetchMock).toHaveBeenLastCalledWith(new Request(info, { ...init, headers }));

fetchMock.mockClear();
});
Expand Down
12 changes: 12 additions & 0 deletions tests/customer/API.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,18 @@ describe('Customer', () => {
fetchMock.mockClear();
});

it('supports Request instances in .fetch()', async () => {
fetchMock.mockImplementation(() => Promise.resolve(new Response(null)));

const api = new CustomerAPI(commonInit);
const url = api.base.toString();

await api.fetch(new Request(url));

expect(fetchMock).toHaveBeenCalledWith(new Request(url, { headers: commonHeaders }));
fetchMock.mockClear();
});

it('can create a session with .signIn()', async () => {
fetchMock.mockImplementation(() => Promise.resolve(new Response(JSON.stringify(sampleSession))));

Expand Down

0 comments on commit 7f3c58c

Please sign in to comment.