Skip to content

Commit

Permalink
✨(frontend) add auth token into generated api
Browse files Browse the repository at this point in the history
Generated api client need's to handle joanie authentification
  • Loading branch information
rlecellier committed Nov 21, 2023
1 parent bfadf58 commit bb4c252
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 7 deletions.
34 changes: 34 additions & 0 deletions src/frontend/js/api/joanie/__specs__/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import fetchMock from 'fetch-mock';
import { RichieContextFactory as mockRichieContextFactory } from 'utils/test/factories/richie';
import { RICHIE_USER_TOKEN } from 'settings';

import { joanieApi } from '..';

jest.mock('utils/context', () => ({
__esModule: true,
default: mockRichieContextFactory({
authentication: { backend: 'fonzie', endpoint: 'https://demo.endpoint' },
joanie_backend: { endpoint: 'https://joanie.endpoint' },
}).one(),
}));

describe('joanieApi', () => {
it('test', async () => {
fetchMock.get('https://joanie.endpoint/api/v1.0/addresses/addressId/', []);
await joanieApi.api.apiV10AddressesRetrieve('addressId');

let lastCall = fetchMock.lastCall();
const visitorHeader = lastCall && lastCall[1]?.headers;
// TS see visitorHeader has HeadersInit instead of Headers and
// didn't accept get() as a possible function.
// @ts-ignore
expect(visitorHeader?.get('Authorization')).toBeNull();

sessionStorage.setItem(RICHIE_USER_TOKEN, 'TEST_TOKEN');
await joanieApi.api.apiV10AddressesRetrieve('addressId');
lastCall = fetchMock.lastCall();
const userHeader = lastCall && lastCall[1]?.headers;
// @ts-ignore
expect(userHeader?.get('Authorization')).toBe('Bearer TEST_TOKEN');
});
});
18 changes: 11 additions & 7 deletions src/frontend/js/api/joanie/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import context from 'utils/context';
import { JOANIE_API_VERSION } from 'settings';
import { ApiClientJoanie, OpenAPIConfig } from './gen';
import { JOANIE_API_VERSION, RICHIE_USER_TOKEN } from 'settings';
import { ApiClientJoanie, ApiError, OpenAPIConfig } from './gen';

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

// TODO add auth with jwt
const config: OpenAPIConfig = {
BASE: getAPIEndpoint(),
VERSION: '1',
WITH_CREDENTIALS: true,
CREDENTIALS: 'include',
// TOKEN:
WITH_CREDENTIALS: false,
CREDENTIALS: 'omit',
TOKEN: async () => {
return sessionStorage.getItem(RICHIE_USER_TOKEN) || '';
},
};

export const joanieApi = new ApiClientJoanie(config);
export * from './hooks';

export const isApiError = (error: unknown): error is ApiError => {
return (error as ApiError).name === 'ApiError';
};

0 comments on commit bb4c252

Please sign in to comment.