From ed2f056a39c9b8bd1dd602fabc6fd7d9e40d7752 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20de=20Juvigny?= <8087692+remidej@users.noreply.github.com> Date: Fri, 9 Aug 2024 17:23:55 +0200 Subject: [PATCH] fix: don't check uniqueness for empty strings (#20985) * fix: don't check uniqueness for empty strings * chore: add api test --- .../core/src/services/entity-validator/validators.ts | 6 +++--- .../strapi/document-service/uniqueness.test.api.ts | 12 ++++++++++++ 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/packages/core/core/src/services/entity-validator/validators.ts b/packages/core/core/src/services/entity-validator/validators.ts index a50f945841..77dc4d743a 100644 --- a/packages/core/core/src/services/entity-validator/validators.ts +++ b/packages/core/core/src/services/entity-validator/validators.ts @@ -339,10 +339,10 @@ const addUniqueValidator = ( 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; } diff --git a/tests/api/core/strapi/document-service/uniqueness.test.api.ts b/tests/api/core/strapi/document-service/uniqueness.test.api.ts index 40f023a5f3..2489ffae7a 100644 --- a/tests/api/core/strapi/document-service/uniqueness.test.api.ts +++ b/tests/api/core/strapi/document-service/uniqueness.test.api.ts @@ -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', () => {