Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(chore) generate joanie api client #1901

Draft
wants to merge 12 commits into
base: master
Choose a base branch
from
Draft
Prev Previous commit
Next Next commit
✨(frontend) add jwt token into joanie generated api
rlecellier committed Mar 6, 2023
commit 314152cb9bbfb7992d8f5ff94a03e0c3dc4fdd05
35 changes: 35 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,35 @@
import fetchMock from 'fetch-mock';
import * as mockFactories from 'utils/test/factories';
import { RICHIE_USER_TOKEN } from 'settings';

import { joanieApi } from '..';

jest.mock('utils/context', () => ({
__esModule: true,
default: mockFactories
.ContextFactory({
joanie_backend: { endpoint: 'https://joanie.endpoint' },
})
.generate(),
}));

describe('joanieApi', () => {
it('test', async () => {
fetchMock.get('https://joanie.endpoint/api/v1.0/addresses/addressId/', []);
await joanieApi.addresses.addressesRead({ id: '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.addresses.addressesRead({ id: '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.
@@ -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';
};