Add small fix and adapt tests

This commit is contained in:
Christian Capeans 2023-03-15 17:32:25 +01:00
parent 41a5c79994
commit e1b78e05c4
7 changed files with 84 additions and 63 deletions

View File

@ -4,21 +4,21 @@ import { useIntl } from 'react-intl';
import { Select, Option } from '@strapi/design-system';
const TokenTypeSelect = ({ errors, values, onChange, canEditInputs, options, label }) => {
const TokenTypeSelect = ({ name, errors, values, onChange, canEditInputs, options, label }) => {
const { formatMessage } = useIntl();
return (
<Select
name="type"
name={name}
label={formatMessage({
id: label.id,
defaultMessage: label.defaultMessage,
})}
value={values?.type}
value={values && values[name]}
error={
errors.type
errors[name]
? formatMessage(
errors.type?.id ? errors.type : { id: errors.type, defaultMessage: errors.type }
errors[name]?.id ? errors[name] : { id: errors[name], defaultMessage: errors[name] }
)
: null
}
@ -38,6 +38,7 @@ const TokenTypeSelect = ({ errors, values, onChange, canEditInputs, options, lab
};
TokenTypeSelect.propTypes = {
name: PropTypes.string,
options: PropTypes.arrayOf(
PropTypes.shape({
label: PropTypes.shape({
@ -62,6 +63,7 @@ TokenTypeSelect.propTypes = {
};
TokenTypeSelect.defaultProps = {
name: 'type',
errors: {},
options: [],
};

View File

@ -84,8 +84,9 @@ const FormTransferTokenContainer = ({
token={transferToken}
/>
</GridItem>
<GridItem key="type" col={6} xs={12}>
<GridItem key="permissions" col={6} xs={12}>
<TokenTypeSelect
name="permissions"
values={values}
errors={errors}
label={{
@ -93,7 +94,7 @@ const FormTransferTokenContainer = ({
defaultMessage: 'Token type',
}}
onChange={(value) => {
onChange({ target: { name: 'type', value } });
onChange({ target: { name: 'permissions', value } });
}}
options={typeOptions}
canEditInputs={canEditInputs}

View File

@ -92,7 +92,7 @@ const TransferTokenCreateView = () => {
? parseInt(body.lifespan, 10)
: null;
const permissions = body.type.split('-');
const permissions = body.permissions.split('-');
try {
const {
@ -106,7 +106,6 @@ const TransferTokenCreateView = () => {
: await put(`/admin/transfer/tokens/${id}`, {
name: body.name,
description: body.description,
type: body.type,
permissions,
});
@ -132,9 +131,9 @@ const TransferTokenCreateView = () => {
defaultMessage: 'Transfer Token successfully edited',
}),
});
console.log('transferToken', transferToken);
trackUsageRef.current(isCreating ? 'didCreateToken' : 'didEditToken', {
type: transferToken?.type,
type: transferToken?.permissions,
tokenType: TRANSFER_TOKEN_TYPE,
});
} catch (err) {
@ -175,7 +174,7 @@ const TransferTokenCreateView = () => {
lifespan: transferToken?.lifespan
? transferToken.lifespan.toString()
: transferToken?.lifespan,
type: transferToken?.permissions.join('-'),
permissions: transferToken?.permissions.join('-'),
}}
enableReinitialize
onSubmit={(body, actions) => handleSubmit(body, actions)}

View File

@ -5,7 +5,7 @@ const schema = yup.object().shape({
name: yup.string(translatedErrors.string).required(translatedErrors.required),
description: yup.string().nullable(),
lifespan: yup.number().integer().min(0).nullable().defined(translatedErrors.required),
type: yup.string(translatedErrors.string).required(translatedErrors.required),
permissions: yup.string(translatedErrors.string).required(translatedErrors.required),
});
export default schema;

View File

@ -149,37 +149,39 @@ const update = async (id, attributes) => {
},
});
const currentPermissionsResult = await strapi.entityService.load(
TRANSFER_TOKEN_UID,
updatedToken,
'permissions'
);
if (attributes.permissions) {
const currentPermissionsResult = await strapi.entityService.load(
TRANSFER_TOKEN_UID,
updatedToken,
'permissions'
);
const currentPermissions = map('action', currentPermissionsResult || []);
const newPermissions = uniq(attributes.permissions);
const currentPermissions = map('action', currentPermissionsResult || []);
const newPermissions = uniq(attributes.permissions);
const actionsToDelete = difference(currentPermissions, newPermissions);
const actionsToAdd = difference(newPermissions, currentPermissions);
const actionsToDelete = difference(currentPermissions, newPermissions);
const actionsToAdd = difference(newPermissions, currentPermissions);
// TODO: improve efficiency here
// method using a loop -- works but very inefficient
await Promise.all(
actionsToDelete.map((action) =>
strapi.query(TRANSFER_TOKEN_PERMISSION_UID).delete({
where: { action, token: id },
})
)
);
// TODO: improve efficiency here
// method using a loop -- works but very inefficient
await Promise.all(
actionsToDelete.map((action) =>
strapi.query(TRANSFER_TOKEN_PERMISSION_UID).delete({
where: { action, token: id },
})
)
);
// TODO: improve efficiency here
// using a loop -- works but very inefficient
await Promise.all(
actionsToAdd.map((action) =>
strapi.query(TRANSFER_TOKEN_PERMISSION_UID).create({
data: { action, token: id },
})
)
);
// TODO: improve efficiency here
// using a loop -- works but very inefficient
await Promise.all(
actionsToAdd.map((action) =>
strapi.query(TRANSFER_TOKEN_PERMISSION_UID).create({
data: { action, token: id },
})
)
);
}
// retrieve permissions
const permissionsFromDb = await strapi.entityService.load(

View File

@ -40,6 +40,7 @@ describe('Admin Transfer Token CRUD (api)', () => {
const body = {
name: `transfer_token_${String(currentTokens)}`,
description: 'generic description',
permissions: ['push', 'pull'],
...token,
};
@ -69,7 +70,7 @@ describe('Admin Transfer Token CRUD (api)', () => {
error: {
status: 400,
name: 'ValidationError',
message: '2 errors occurred',
message: '3 errors occurred',
details: {
errors: [
{
@ -82,6 +83,11 @@ describe('Admin Transfer Token CRUD (api)', () => {
name: 'ValidationError',
message: 'name is a required field',
},
{
path: ['permissions'],
name: 'ValidationError',
message: 'permissions is a required field',
},
],
},
},
@ -92,6 +98,7 @@ describe('Admin Transfer Token CRUD (api)', () => {
const body = {
name: 'transfer-token_tests-no-lifespan',
description: 'transfer-token_tests-description',
permissions: ['push'],
};
const res = await rq({
@ -104,7 +111,7 @@ describe('Admin Transfer Token CRUD (api)', () => {
expect(res.body.data).toStrictEqual({
accessKey: expect.any(String),
name: body.name,
permissions: [],
permissions: body.permissions,
description: body.description,
id: expect.any(Number),
createdAt: expect.toBeISODate(),
@ -123,6 +130,7 @@ describe('Admin Transfer Token CRUD (api)', () => {
name: 'transfer-token_tests-lifespan7',
description: 'transfer-token_tests-description',
lifespan: 7 * 24 * 60 * 60 * 1000, // 7 days
permissions: ['pull'],
};
const res = await rq({
@ -135,7 +143,7 @@ describe('Admin Transfer Token CRUD (api)', () => {
expect(res.body.data).toStrictEqual({
accessKey: expect.any(String),
name: body.name,
permissions: [],
permissions: body.permissions,
description: body.description,
id: expect.any(Number),
createdAt: expect.toBeISODate(),
@ -160,6 +168,7 @@ describe('Admin Transfer Token CRUD (api)', () => {
name: 'transfer-token_tests-lifespan30',
description: 'transfer-token_tests-description',
lifespan: 30 * 24 * 60 * 60 * 1000, // 30 days
permissions: ['push'],
};
const res = await rq({
@ -172,7 +181,7 @@ describe('Admin Transfer Token CRUD (api)', () => {
expect(res.body.data).toStrictEqual({
accessKey: expect.any(String),
name: body.name,
permissions: [],
permissions: body.permissions,
description: body.description,
id: expect.any(Number),
createdAt: expect.toBeISODate(),
@ -197,6 +206,7 @@ describe('Admin Transfer Token CRUD (api)', () => {
name: 'transfer-token_tests-lifespan90',
description: 'transfer-token_tests-description',
lifespan: 90 * 24 * 60 * 60 * 1000, // 90 days
permissions: ['push', 'pull'],
};
const res = await rq({
@ -209,7 +219,7 @@ describe('Admin Transfer Token CRUD (api)', () => {
expect(res.body.data).toStrictEqual({
accessKey: expect.any(String),
name: body.name,
permissions: [],
permissions: body.permissions,
description: body.description,
id: expect.any(Number),
createdAt: expect.toBeISODate(),
@ -231,6 +241,7 @@ describe('Admin Transfer Token CRUD (api)', () => {
name: 'transfer-token_tests-nulllifespan',
description: 'transfer-token_tests-description',
lifespan: null,
permissions: ['push', 'pull'],
};
const res = await rq({
@ -243,7 +254,7 @@ describe('Admin Transfer Token CRUD (api)', () => {
expect(res.body.data).toStrictEqual({
accessKey: expect.any(String),
name: body.name,
permissions: [],
permissions: body.permissions,
description: body.description,
id: expect.any(Number),
createdAt: expect.toBeISODate(),
@ -259,6 +270,7 @@ describe('Admin Transfer Token CRUD (api)', () => {
name: 'transfer-token_tests-lifespan',
description: 'transfer-token_tests-description',
lifespan: -1,
permissions: ['push', 'pull'],
};
const res = await rq({
@ -286,9 +298,10 @@ describe('Admin Transfer Token CRUD (api)', () => {
});
});
test('Creates an transfer token without a description (successfully)', async () => {
test('Creates a transfer token without a description (successfully)', async () => {
const body = {
name: 'transfer-token_tests-without-description',
permissions: ['push', 'pull'],
};
const res = await rq({
@ -301,7 +314,7 @@ describe('Admin Transfer Token CRUD (api)', () => {
expect(res.body.data).toMatchObject({
accessKey: expect.any(String),
name: body.name,
permissions: [],
permissions: body.permissions,
description: '',
id: expect.any(Number),
createdAt: expect.any(String),
@ -312,10 +325,11 @@ describe('Admin Transfer Token CRUD (api)', () => {
});
});
test('Creates an transfer token with trimmed description and name (successfully)', async () => {
test('Creates a transfer token with trimmed description and name (successfully)', async () => {
const body = {
name: ' transfer-token_tests-spaces-at-the-end ',
description: ' transfer-token_tests-description-with-spaces-at-the-end ',
permissions: ['push', 'pull'],
};
const res = await rq({
@ -328,7 +342,7 @@ describe('Admin Transfer Token CRUD (api)', () => {
expect(res.body.data).toMatchObject({
accessKey: expect.any(String),
name: 'transfer-token_tests-spaces-at-the-end',
permissions: [],
permissions: body.permissions,
description: 'transfer-token_tests-description-with-spaces-at-the-end',
id: expect.any(Number),
createdAt: expect.any(String),
@ -377,17 +391,18 @@ describe('Admin Transfer Token CRUD (api)', () => {
});
expect(res.statusCode).toBe(200);
expect(res.body.data).toMatchObject({
name: token.name,
permissions: token.permissions,
description: token.description,
id: token.id,
createdAt: token.createdAt,
lastUsedAt: null,
updatedAt: expect.any(String),
expiresAt: null,
lifespan: null,
});
expect(res.body.data).toEqual(
expect.objectContaining({
name: token.name,
description: token.description,
id: token.id,
createdAt: token.createdAt,
lastUsedAt: null,
updatedAt: expect.any(String),
expiresAt: null,
lifespan: null,
})
);
});
test('Does not return an error if the resource to delete does not exist', async () => {
@ -451,6 +466,7 @@ describe('Admin Transfer Token CRUD (api)', () => {
const updatedBody = {
name: 'transfer-token_tests-updated-name',
description: 'transfer-token_tests-description',
permissions: ['push'],
};
const updatedRes = await rq({
@ -462,7 +478,7 @@ describe('Admin Transfer Token CRUD (api)', () => {
expect(updatedRes.statusCode).toBe(200);
expect(updatedRes.body.data).toMatchObject({
name: updatedBody.name,
permissions: [],
permissions: updatedBody.permissions,
description: updatedBody.description,
id: token.id,
createdAt: token.createdAt,
@ -477,6 +493,7 @@ describe('Admin Transfer Token CRUD (api)', () => {
const body = {
name: 'transfer-token_tests-updated-name',
description: 'transfer-token_tests-updated-description',
permissions: ['push'],
};
const res = await rq({

View File

@ -31,7 +31,7 @@ const transferTokenUpdateSchema = yup
.array()
.min(1)
.of(yup.string().oneOf(Object.values(constants.TRANSFER_TOKEN_TYPE)))
.required(),
.nullable(),
})
.noUnknown()
.strict();