fix: don't check uniqueness for empty strings (#20985)

* fix: don't check uniqueness for empty strings

* chore: add api test
This commit is contained in:
Rémi de Juvigny 2024-08-09 17:23:55 +02:00 committed by GitHub
parent 22092ac004
commit ed2f056a39
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 15 additions and 3 deletions

View File

@ -339,10 +339,10 @@ const addUniqueValidator = <T extends yup.AnySchema>(
return validator.test('unique', 'This attribute must be unique', async (value) => {
/**
* If the attribute value is `null` we want to skip the unique validation.
* Otherwise it'll only accept a single `null` entry in the database.
* If the attribute value is `null` or an empty string we want to skip the unique validation.
* Otherwise it'll only accept a single entry with that value in the database.
*/
if (_.isNil(value)) {
if (_.isNil(value) || value === '') {
return true;
}

View File

@ -65,6 +65,18 @@ describe('Document Service', () => {
strapi.documents(CATEGORY_UID).publish({ documentId: newCategory.documentId })
).rejects.toThrow();
});
it('can save and publish multiple entries with an empty string in a unique field', async () => {
// Create two categories with empty names (which is a unique field)
const category = await strapi.documents(CATEGORY_UID).create({ data: { name: '' } });
expect(category).toBeDefined();
const category2 = await strapi.documents(CATEGORY_UID).create({ data: { name: '' } });
expect(category2).toBeDefined();
// Publish categories, no error should be thrown
await strapi.documents(CATEGORY_UID).publish({ documentId: category.documentId });
await strapi.documents(CATEGORY_UID).publish({ documentId: category2.documentId });
});
});
describe('Component unique fields', () => {