@@ -9,9 +9,8 @@ const { NotFoundError } = require('@strapi/utils').errors;
99
1010module . exports = createCoreController ( 'api::study.study' , ( { strapi } ) => ( {
1111 async find ( ctx ) {
12-
1312 // If not providing a dataset id, return only studies that are listed
14- if ( ! ctx . query . filters ?. datasets ?. id ?. $eq ) {
13+ if ( ! ctx . query . filters ?. datasets ?. id ?. $eq ) {
1514 ctx . query . filters = {
1615 ...ctx . query . filters ,
1716 is_listed : true ,
@@ -79,7 +78,7 @@ module.exports = createCoreController('api::study.study', ({ strapi }) => ({
7978 fields : [ 'name' , 'description' , 'type' , 'category' ] ,
8079 } ,
8180 cover_dataset : {
82- fields : [ false ] ,
81+ fields : [ 'id' ] ,
8382 populate : [ 'media' ] ,
8483 } ,
8584 } ,
@@ -114,6 +113,33 @@ module.exports = createCoreController('api::study.study', ({ strapi }) => ({
114113 } ;
115114 }
116115
116+ // If sorting by publication date, get studies and manually sort
117+ // as nested sorting returns duplicates (https://github.com/strapi/strapi/issues/11892)
118+ const [ sort , order = 'asc' ] = ctx . query . sort ?. split ( ':' ) || [ ] ;
119+ if ( sort === 'publications.date' ) {
120+ const studies = await strapi . entityService . findMany (
121+ 'api::study.study' ,
122+ ctx . query
123+ ) ;
124+
125+ studies . sort ( ( a , b ) => {
126+ const aLatest = Math . max (
127+ ...( a . publications || [ ] ) . map ( ( p ) => new Date ( p . date ) ) ,
128+ 0
129+ ) ;
130+ const bLatest = Math . max (
131+ ...( b . publications || [ ] ) . map ( ( p ) => new Date ( p . date ) ) ,
132+ 0
133+ ) ;
134+ return order === 'asc' ? aLatest - bLatest : bLatest - aLatest ;
135+ } ) ;
136+
137+ const { results : paginatedStudies , meta } =
138+ strapi . config . functions . paginate ( studies , ctx . query . pagination || { } ) ;
139+
140+ return this . transformResponse ( paginatedStudies , meta ) ;
141+ }
142+
117143 return await super . find ( ctx ) ;
118144 } ,
119145 async findOne ( ctx ) {
@@ -200,7 +226,7 @@ module.exports = createCoreController('api::study.study', ({ strapi }) => ({
200226 populate : [ 'media' , 'data' , 'resources' ] ,
201227 } ,
202228 resources : true ,
203- media : { fields : [ 'title' , 'type' ] , populate : [ 'file' ] } ,
229+ media : { fields : [ 'title' , 'type' ] , populate : [ 'file' ] } ,
204230 cover_dataset : {
205231 fields : [ ] ,
206232 populate : [ 'media' ] ,
0 commit comments