Add logout helper function

This commit is contained in:
Bill Thornton 2021-09-21 10:18:49 -04:00
parent 0dafb59d2d
commit c1e08e9b79
4 changed files with 39 additions and 1 deletions

View File

@ -62,4 +62,8 @@ console.log('Auth =>', auth.data);
// requests that require authentication can be made normally
const libraries = await api.libraryApi.getMediaFolders();
console.log('Libraries =>', libraries.data);
// A helper method for logging out the current user has been added to the
// SDK so the internal state is updated correctly.
await api.logout();
```

View File

@ -15,14 +15,19 @@ import { getAuthorizationHeader } from '../utils';
jest.mock('axios');
const mockAxios = mocked(axios, true);
const TEST_ACCESS_TOKEN = 'TEST-ACCESS-TOKEN';
/**
* Api class tests.
*
* @group unit
*/
describe('Api', () => {
afterEach(() => {
jest.clearAllMocks();
});
it('should authenticate and update state', async () => {
const TEST_ACCESS_TOKEN = 'TEST-ACCESS-TOKEN';
const USER_CREDENTIALS = {
Username: 'test',
Pw: ''
@ -45,6 +50,21 @@ describe('Api', () => {
expect(api.accessToken).toBe(TEST_ACCESS_TOKEN);
});
it('should logout and update state', async () => {
const api = new Api(SERVER_URL, TEST_CLIENT, TEST_DEVICE, TEST_ACCESS_TOKEN);
expect(api.accessToken).toBe(TEST_ACCESS_TOKEN);
await api.logout();
expect(mockAxios.request.mock.calls).toHaveLength(1);
const requestData = mockAxios.request.mock.calls[0][0];
expect(requestData.url).toBe(`${SERVER_URL}/Sessions/Logout`);
expect(api.accessToken).toBe('');
});
it('should return the correct authorization header value', () => {
const api = new Api(SERVER_URL, TEST_CLIENT, TEST_DEVICE);
expect(api.authorizationHeader).toBe(getAuthorizationHeader(TEST_CLIENT, TEST_DEVICE));

View File

@ -49,6 +49,8 @@ describe('Test the Base SDK', () => {
const auth = await api.authenticateUserByName({ Username: 'demo', Pw: '' });
// console.log('Auth =>', auth.data);
expect(auth.data).toBeTruthy();
await api.logout();
});
it('library api', async () => {
@ -63,5 +65,7 @@ describe('Test the Base SDK', () => {
const libraries = await api.libraryApi.getMediaFolders();
// console.log('Libraries =>', libraries.data);
expect(libraries.data).toBeTruthy();
await api.logout();
});
});

View File

@ -58,6 +58,16 @@ export class Api {
});
}
/**
* Convenience method for logging out and updating the internal state.
*/
logout(): Promise<AxiosResponse> {
return this.sessionApi.reportSessionEnded().then(response => {
this.accessToken = '';
return response;
});
}
get authorizationHeader(): string {
return getAuthorizationHeader(this.clientInfo, this.deviceInfo, this.accessToken);
}