diff --git a/packages/core/strapi/lib/core-api/controller/__tests__/transform.test.js b/packages/core/strapi/lib/core-api/controller/__tests__/transform.test.js index 2928cc415b..efc5f6eb1e 100644 --- a/packages/core/strapi/lib/core-api/controller/__tests__/transform.test.js +++ b/packages/core/strapi/lib/core-api/controller/__tests__/transform.test.js @@ -119,4 +119,108 @@ describe('Transforms', () => { meta: {}, }); }); + + test('Handles relations recursively', () => { + const contentType = { + attributes: { + relation: { + type: 'relation', + target: 'xxx', + }, + }, + }; + + global.strapi = { + contentType() { + return { + attributes: { + nestedRelation: { + type: 'relation', + target: 'xxxx', + }, + }, + }; + }, + }; + + expect( + transforms.transformResponse( + { + id: 1, + title: 'Hello', + relation: [{ id: 1, value: 'test', nestedRelation: { id: 2, foo: 'bar' } }], + }, + undefined, + { contentType } + ) + ).toStrictEqual({ + data: { + id: 1, + attributes: { + title: 'Hello', + relation: { + data: [ + { + id: 1, + attributes: { + value: 'test', + nestedRelation: { + data: { + id: 2, + attributes: { + foo: 'bar', + }, + }, + }, + }, + }, + ], + }, + }, + }, + meta: {}, + }); + }); + + test('Handles media like relations', () => { + const contentType = { + attributes: { + media: { + type: 'media', + }, + }, + }; + + global.strapi = { + contentType() { + return undefined; + }, + }; + + expect( + transforms.transformResponse( + { id: 1, title: 'Hello', media: [{ id: 1, value: 'test' }] }, + undefined, + { contentType } + ) + ).toStrictEqual({ + data: { + id: 1, + attributes: { + title: 'Hello', + media: { + data: [ + { + id: 1, + attributes: { + value: 'test', + }, + }, + ], + }, + }, + }, + meta: {}, + }); + }); }); diff --git a/packages/core/strapi/lib/core-api/controller/transform.js b/packages/core/strapi/lib/core-api/controller/transform.js index c2d8802dc9..368ba766e7 100644 --- a/packages/core/strapi/lib/core-api/controller/transform.js +++ b/packages/core/strapi/lib/core-api/controller/transform.js @@ -37,6 +37,10 @@ const transformEntry = (entry, contentType) => { if (attribute && attribute.type === 'relation') { const data = transformEntry(property, strapi.contentType(attribute.target)); + attributeValues[key] = { data }; + } else if (attribute && attribute.type === 'media') { + const data = transformEntry(property, strapi.contentType('plugin::upload.file')); + attributeValues[key] = { data }; } else { attributeValues[key] = property;