refactor: remove get-roles GQL query

This commit is contained in:
Rıdvan Akca
2024-03-14 16:35:51 +03:00
parent 9218091c33
commit ecc9379d7e
7 changed files with 12 additions and 163 deletions

View File

@@ -1,9 +0,0 @@
import Role from '../../models/role.js';
const getRoles = async (_parent, params, context) => {
context.currentUser.can('read', 'Role');
return await Role.query().orderBy('name');
};
export default getRoles;

View File

@@ -1,134 +0,0 @@
import { vi, describe, it, expect, beforeEach } from 'vitest';
import request from 'supertest';
import app from '../../app';
import createAuthTokenByUserId from '../../helpers/create-auth-token-by-user-id';
import { createRole } from '../../../test/factories/role';
import { createPermission } from '../../../test/factories/permission';
import { createUser } from '../../../test/factories/user';
import * as license from '../../helpers/license.ee';
describe('graphQL getRoles query', () => {
let currentUserRole,
roleOne,
roleSecond,
query,
userWithPermissions,
userWithoutPermissions,
tokenWithPermissions,
tokenWithoutPermissions;
beforeEach(async () => {
currentUserRole = await createRole({ name: 'Current user role' });
roleOne = await createRole({ name: 'Role one' });
roleSecond = await createRole({ name: 'Role second' });
query = `
query {
getRoles {
id
key
name
description
isAdmin
}
}
`;
await createPermission({
action: 'read',
subject: 'Role',
roleId: currentUserRole.id,
});
userWithPermissions = await createUser({
roleId: currentUserRole.id,
});
userWithoutPermissions = await createUser({
roleId: roleOne.id,
});
tokenWithPermissions = createAuthTokenByUserId(userWithPermissions.id);
tokenWithoutPermissions = createAuthTokenByUserId(
userWithoutPermissions.id
);
});
describe('and with valid license', () => {
beforeEach(async () => {
vi.spyOn(license, 'hasValidLicense').mockResolvedValue(true);
});
describe('and without permissions', () => {
it('should throw not authorized error', async () => {
const response = await request(app)
.post('/graphql')
.set('Authorization', tokenWithoutPermissions)
.send({ query })
.expect(200);
expect(response.body.errors).toBeDefined();
expect(response.body.errors[0].message).toEqual('Not authorized!');
});
});
describe('and correct permissions', () => {
it('should return roles data', async () => {
const response = await request(app)
.post('/graphql')
.set('Authorization', tokenWithPermissions)
.send({ query })
.expect(200);
const expectedResponsePayload = {
data: {
getRoles: [
{
description: currentUserRole.description,
id: currentUserRole.id,
isAdmin: currentUserRole.key === 'admin',
key: currentUserRole.key,
name: currentUserRole.name,
},
{
description: roleOne.description,
id: roleOne.id,
isAdmin: roleOne.key === 'admin',
key: roleOne.key,
name: roleOne.name,
},
{
description: roleSecond.description,
id: roleSecond.id,
isAdmin: roleSecond.key === 'admin',
key: roleSecond.key,
name: roleSecond.name,
},
],
},
};
expect(response.body).toEqual(expectedResponsePayload);
});
});
});
describe('and without valid license', () => {
beforeEach(async () => {
vi.spyOn(license, 'hasValidLicense').mockResolvedValue(false);
});
describe('and correct permissions', () => {
it('should throw not authorized error', async () => {
const response = await request(app)
.post('/graphql')
.set('Authorization', tokenWithPermissions)
.send({ query })
.expect(200);
expect(response.body.errors).toBeDefined();
expect(response.body.errors[0].message).toEqual('Not authorized!');
});
});
});
});

View File

@@ -13,7 +13,6 @@ import getInvoices from './queries/get-invoices.ee.js';
import getNotifications from './queries/get-notifications.js'; import getNotifications from './queries/get-notifications.js';
import getPermissionCatalog from './queries/get-permission-catalog.ee.js'; import getPermissionCatalog from './queries/get-permission-catalog.ee.js';
import getRole from './queries/get-role.ee.js'; import getRole from './queries/get-role.ee.js';
import getRoles from './queries/get-roles.ee.js';
import getSamlAuthProviderRoleMappings from './queries/get-saml-auth-provider-role-mappings.ee.js'; import getSamlAuthProviderRoleMappings from './queries/get-saml-auth-provider-role-mappings.ee.js';
import getSamlAuthProvider from './queries/get-saml-auth-provider.ee.js'; import getSamlAuthProvider from './queries/get-saml-auth-provider.ee.js';
import getStepWithTestExecutions from './queries/get-step-with-test-executions.js'; import getStepWithTestExecutions from './queries/get-step-with-test-executions.js';
@@ -40,7 +39,6 @@ const queryResolvers = {
getNotifications, getNotifications,
getPermissionCatalog, getPermissionCatalog,
getRole, getRole,
getRoles,
getSamlAuthProvider, getSamlAuthProvider,
getSamlAuthProviderRoleMappings, getSamlAuthProviderRoleMappings,
getStepWithTestExecutions, getStepWithTestExecutions,

View File

@@ -29,7 +29,6 @@ type Query {
getInvoices: [Invoice] getInvoices: [Invoice]
getPermissionCatalog: PermissionCatalog getPermissionCatalog: PermissionCatalog
getRole(id: String!): Role getRole(id: String!): Role
getRoles: [Role]
getNotifications: [Notification] getNotifications: [Notification]
getSamlAuthProvider: SamlAuthProvider getSamlAuthProvider: SamlAuthProvider
getSamlAuthProviderRoleMappings(id: String!): [SamlAuthProvidersRoleMapping] getSamlAuthProviderRoleMappings(id: String!): [SamlAuthProvidersRoleMapping]

View File

@@ -4,6 +4,8 @@ import DeleteIcon from '@mui/icons-material/Delete';
import IconButton from '@mui/material/IconButton'; import IconButton from '@mui/material/IconButton';
import useEnqueueSnackbar from 'hooks/useEnqueueSnackbar'; import useEnqueueSnackbar from 'hooks/useEnqueueSnackbar';
import * as React from 'react'; import * as React from 'react';
import { useQueryClient } from '@tanstack/react-query';
import Can from 'components/Can'; import Can from 'components/Can';
import ConfirmationDialog from 'components/ConfirmationDialog'; import ConfirmationDialog from 'components/ConfirmationDialog';
import { DELETE_ROLE } from 'graphql/mutations/delete-role.ee'; import { DELETE_ROLE } from 'graphql/mutations/delete-role.ee';
@@ -12,15 +14,18 @@ import useFormatMessage from 'hooks/useFormatMessage';
function DeleteRoleButton(props) { function DeleteRoleButton(props) {
const { disabled, roleId } = props; const { disabled, roleId } = props;
const [showConfirmation, setShowConfirmation] = React.useState(false); const [showConfirmation, setShowConfirmation] = React.useState(false);
const [deleteRole] = useMutation(DELETE_ROLE, {
variables: { input: { id: roleId } },
refetchQueries: ['GetRoles'],
});
const formatMessage = useFormatMessage(); const formatMessage = useFormatMessage();
const enqueueSnackbar = useEnqueueSnackbar(); const enqueueSnackbar = useEnqueueSnackbar();
const queryClient = useQueryClient();
const [deleteRole] = useMutation(DELETE_ROLE, {
variables: { input: { id: roleId } },
});
const handleConfirm = React.useCallback(async () => { const handleConfirm = React.useCallback(async () => {
try { try {
await deleteRole(); await deleteRole();
queryClient.invalidateQueries({ queryKey: ['roles'] });
setShowConfirmation(false); setShowConfirmation(false);
enqueueSnackbar(formatMessage('deleteRoleButton.successfullyDeleted'), { enqueueSnackbar(formatMessage('deleteRoleButton.successfullyDeleted'), {
variant: 'success', variant: 'success',
@@ -31,7 +36,8 @@ function DeleteRoleButton(props) {
} catch (error) { } catch (error) {
throw new Error('Failed while deleting!'); throw new Error('Failed while deleting!');
} }
}, [deleteRole]); }, [deleteRole, enqueueSnackbar, formatMessage, queryClient]);
return ( return (
<> <>
<Can I="delete" a="Role" passThrough> <Can I="delete" a="Role" passThrough>

View File

@@ -1,12 +0,0 @@
import { gql } from '@apollo/client';
export const GET_ROLES = gql`
query GetRoles {
getRoles {
id
key
name
description
isAdmin
}
}
`;

View File

@@ -3,6 +3,7 @@ import api from 'helpers/api';
export default function useRoles() { export default function useRoles() {
const query = useQuery({ const query = useQuery({
staleTime: 0,
queryKey: ['roles'], queryKey: ['roles'],
queryFn: async ({ signal }) => { queryFn: async ({ signal }) => {
const { data } = await api.get('/v1/admin/roles', { const { data } = await api.get('/v1/admin/roles', {