From 253f14450130fdbde75e7619df7029377acd560a Mon Sep 17 00:00:00 2001 From: Naz Date: Thu, 1 Jun 2023 13:43:20 +0700 Subject: [PATCH] Fixed fromDTO collection mapping refs https://github.com/TryGhost/Team/issues/3260 - Whenever properties of the DTO are undefined they should be removed to avoid unintentional empty assignments to the stored collection --- ghost/collections/src/CollectionsService.ts | 11 ++++++++++- ghost/collections/test/collections.test.ts | 12 +++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/ghost/collections/src/CollectionsService.ts b/ghost/collections/src/CollectionsService.ts index 31f5028b66..e84652e79e 100644 --- a/ghost/collections/src/CollectionsService.ts +++ b/ghost/collections/src/CollectionsService.ts @@ -74,13 +74,22 @@ export class CollectionsService { } fromDTO(data: any): any { - return { + const mappedDTO: {[index: string]:any} = { title: data.title, slug: data.slug, description: data.description, featureImage: data.feature_image, filter: data.filter }; + + // delete out keys that contain undefined values + for (const key of Object.keys(mappedDTO)) { + if (mappedDTO[key] === undefined) { + delete mappedDTO[key]; + } + } + + return mappedDTO; } async createCollection(data: CollectionInputDTO): Promise { diff --git a/ghost/collections/test/collections.test.ts b/ghost/collections/test/collections.test.ts index ad3e3b7f9f..e679ccd342 100644 --- a/ghost/collections/test/collections.test.ts +++ b/ghost/collections/test/collections.test.ts @@ -1,5 +1,5 @@ import assert from 'assert'; -import {CollectionsService, CollectionsRepositoryInMemory} from '../src/index'; +import {CollectionsService, CollectionsRepositoryInMemory, Collection} from '../src/index'; import {posts} from './fixtures/posts'; describe('CollectionsService', function () { @@ -40,6 +40,16 @@ describe('CollectionsService', function () { assert.equal(deletedCollection, null, 'Collection should be deleted'); }); + describe('toDTO', function () { + it('Can map Collection entity to DTO object', async function () { + const collection = await Collection.create({}); + const dto = collectionsService.toDTO(collection); + + assert.equal(dto.id, collection.id, 'DTO should have the same id as the entity'); + assert.equal(dto.title, null, 'DTO should return null if nullable property of the entity is unassigned'); + }); + }); + describe('addPostToCollection', function () { it('Can add a Post to a Collection', async function () { const collection = await collectionsService.createCollection({