@@ -7,21 +7,43 @@ import app from '@adonisjs/core/services/app'
77import fs from 'node:fs'
88
99export default class PostsController {
10- async index ( { request, auth } : HttpContext ) {
11- const { username, page, size } = request . qs ( )
12- const user = username ? ( await User . findBy ( 'username' , username ) ) ! : auth . user !
10+ async index ( { request, response } : HttpContext ) {
11+ const { username, page = 1 , size = 10 , sort = 'desc' } = request . qs ( )
12+ const user = username ? await User . findBy ( 'username' , username ) : undefined
13+ const pageParam = Number ( page )
14+ const sizeParam = Number ( size )
1315
14- const pageParam = Number ( page ) || 1
15- const sizeParam = Number ( size ) || 10
16+ if ( sizeParam > 100 ) {
17+ return response . badRequest ( { error : { message : 'Digite um tamanho válido de 1 a 100' } } )
18+ }
19+ if ( sort && ! [ 'asc' , 'desc' ] . includes ( sort ) ) {
20+ return response . badRequest ( {
21+ error : { message : "Digite um parâmetro de ordenação válido: 'asc' ou 'desc'" } ,
22+ } )
23+ }
24+
25+ if ( ! user ) {
26+ const posts = await Post . query ( )
27+ . orderBy ( 'id' , sort )
28+ . preload ( 'media' )
29+ . preload ( 'user' , ( userQuery : any ) => {
30+ userQuery . select ( [ 'id' , 'fullName' , 'username' ] )
31+ userQuery . preload ( 'avatar' )
32+ } )
33+ . withCount ( 'comments' )
34+ . withCount ( 'likes' )
35+ . forPage ( pageParam , sizeParam )
36+
37+ return posts
38+ }
1639
1740 await user . load ( 'posts' , ( query ) => {
18- query . orderBy ( 'id' , 'desc' )
41+ query . orderBy ( 'id' , sort )
1942 query . preload ( 'media' )
2043 query . preload ( 'user' , ( userQuery : any ) => {
2144 userQuery . select ( [ 'id' , 'fullName' , 'username' ] )
2245 userQuery . preload ( 'avatar' )
2346 } )
24- query . withCount ( 'retweets' )
2547 query . withCount ( 'comments' )
2648 query . withCount ( 'likes' )
2749 query . forPage ( pageParam , sizeParam )
0 commit comments