Skip to content

Commit 0b7dcfb

Browse files
committed
✨(frontend) add jwt token into joanie generated api
1 parent 1252440 commit 0b7dcfb

File tree

2 files changed

+46
-7
lines changed

2 files changed

+46
-7
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import fetchMock from 'fetch-mock';
2+
import * as mockFactories from 'utils/test/factories';
3+
import { RICHIE_USER_TOKEN } from 'settings';
4+
5+
import { joanieApi } from '..';
6+
7+
jest.mock('utils/context', () => ({
8+
__esModule: true,
9+
default: mockFactories
10+
.ContextFactory({
11+
joanie_backend: { endpoint: 'https://joanie.endpoint' },
12+
})
13+
.generate(),
14+
}));
15+
16+
describe('joanieApi', () => {
17+
it('test', async () => {
18+
fetchMock.get('https://joanie.endpoint/api/v1.0/addresses/addressId/', []);
19+
await joanieApi.addresses.addressesRead({ id: 'addressId' });
20+
21+
let lastCall = fetchMock.lastCall();
22+
const visitorHeader = lastCall && lastCall[1]?.headers;
23+
// TS see visitorHeader has HeadersInit instead of Headers and
24+
// didn't accept get() as a possible function.
25+
// @ts-ignore
26+
expect(visitorHeader?.get('Authorization')).toBeNull();
27+
28+
sessionStorage.setItem(RICHIE_USER_TOKEN, 'TEST_TOKEN');
29+
await joanieApi.addresses.addressesRead({ id: 'addressId' });
30+
lastCall = fetchMock.lastCall();
31+
const userHeader = lastCall && lastCall[1]?.headers;
32+
// @ts-ignore
33+
expect(userHeader?.get('Authorization')).toBe('Bearer TEST_TOKEN');
34+
});
35+
});

src/frontend/js/api/joanie/index.ts

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import context from 'utils/context';
2-
import { JOANIE_API_VERSION } from 'settings';
3-
import { ApiClientJoanie, OpenAPIConfig } from './gen';
2+
import { JOANIE_API_VERSION, RICHIE_USER_TOKEN } from 'settings';
3+
import { ApiClientJoanie, ApiError, OpenAPIConfig } from './gen';
44

55
/**
66
* Build Joanie API Routes interface.
@@ -16,14 +16,18 @@ const getAPIEndpoint = () => {
1616
return `${endpoint}/api/${version}`;
1717
};
1818

19-
// TODO add auth with jwt
2019
const config: OpenAPIConfig = {
2120
BASE: getAPIEndpoint(),
2221
VERSION: '1',
23-
WITH_CREDENTIALS: true,
24-
CREDENTIALS: 'include',
25-
// TOKEN:
22+
WITH_CREDENTIALS: false,
23+
CREDENTIALS: 'omit',
24+
TOKEN: async () => {
25+
return sessionStorage.getItem(RICHIE_USER_TOKEN) || '';
26+
},
2627
};
2728

2829
export const joanieApi = new ApiClientJoanie(config);
29-
export * from './hooks';
30+
31+
export const isApiError = (error: unknown): error is ApiError => {
32+
return (error as ApiError).name === 'ApiError';
33+
};

0 commit comments

Comments
 (0)