Skip to content

Commit

Permalink
Add: Add a hook to load the user's capabilities from the backend
Browse files Browse the repository at this point in the history
The capabilities of the user are provided via a react context and
therefore it should be able to load them independently from the redux
store.
  • Loading branch information
bjoernricks committed Jun 6, 2024
1 parent 411b94c commit 53b033e
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 0 deletions.
46 changes: 46 additions & 0 deletions src/web/hooks/__tests__/useLoadCapabilities.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/* SPDX-FileCopyrightText: 2024 Greenbone AG
*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

import {describe, test, expect, testing} from '@gsa/testing';

import {rendererWith, screen, wait} from 'web/utils/testing';

import useLoadCapabilities from '../useLoadCapabilities';

const TestComponent = () => {
const capabilities = useLoadCapabilities();
return (
<>
{capabilities &&
capabilities.map(capability => {
return (
<div data-testid="capability" key={capability.name}>
{capability.name}
</div>
);
})}
</>
);
};

describe('useLoadCapabilities tests', () => {
test('should load capabilities', async () => {
const capabilities = [{name: 'cap_1'}, {name: 'cap_2'}];
const response = {data: capabilities};
const gmp = {
user: {
currentCapabilities: testing.fn(() => Promise.resolve(response)),
},
};
const {render} = rendererWith({gmp});

render(<TestComponent />);

await wait();

expect(gmp.user.currentCapabilities).toHaveBeenCalled();
expect(screen.getAllByTestId('capability').length).toEqual(2);
});
});
45 changes: 45 additions & 0 deletions src/web/hooks/useLoadCapabilities.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/* SPDX-FileCopyrightText: 2024 Greenbone AG
*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

import {useEffect, useState} from 'react';

import logger from 'gmp/log';
import Capabilities from 'gmp/capabilities/capabilities';

import useGmp from '../utils/useGmp';

const log = logger.getLogger('web.useLoadCapabilities');

/**
* Hook to load the user's capabilities from the backend
*/
const useLoadCapabilities = () => {
const gmp = useGmp();
const [capabilities, setCapabilities] = useState();

useEffect(() => {
gmp.user
.currentCapabilities()
.then(response => {
const loadedCapabilities = response.data;
log.debug('User capabilities', loadedCapabilities);
setCapabilities(loadedCapabilities);
})
.catch(rejection => {
if (rejection.isError()) {
log.error(
'An error occurred during fetching capabilities',
rejection,
);
}
// use empty capabilities
setCapabilities(new Capabilities());
});
}, [gmp.user]);

return capabilities;
};

export default useLoadCapabilities;

0 comments on commit 53b033e

Please sign in to comment.