11const Album = require ( "../models/Album" ) ;
22const Song = require ( "../models/Song" ) ;
3- const { isAdmin } = require ( "../utils" ) ;
3+ const {
4+ isAdmin,
5+ calculateTotalDuration,
6+ cleanUpSongsData,
7+ enhanceAlbumWithSongsData,
8+ } = require ( "../utils" ) ;
49const errorHandler = require ( "../middlewares/errorMiddleware" ) ;
5- const cleanUpSongs = ( songs , album ) => {
6- return songs
7- . filter ( ( song ) => song !== null )
8- . map ( ( { albumId, ...songWithoutAlbumId } ) => ( {
9- ...songWithoutAlbumId ,
10- album : album . title ,
11- } ) ) ;
12- } ;
1310
1411const getAlbum = async ( req , res ) => {
1512 try {
@@ -23,15 +20,7 @@ const getAlbum = async (req, res) => {
2320 return res . status ( 404 ) . send ( "Album not found" ) ;
2421 }
2522
26- const songPromises = album . tracks . map ( ( songId ) =>
27- Song . findById ( songId . toString ( ) ) . select ( "-__v" ) . select ( "-_id" ) . lean ( )
28- ) ;
29- const songs = await Promise . all ( songPromises ) ;
30-
31- album . tracks = cleanUpSongs ( songs , album ) ;
32- album . songs = album . tracks . length ;
33-
34- res . json ( album ) ;
23+ res . json ( await enhanceAlbumWithSongsData ( album ) ) ;
3524 } catch ( error ) {
3625 errorHandler ( res , error ) ;
3726 }
@@ -41,14 +30,8 @@ const getAllAlbums = async (req, res) => {
4130 try {
4231 const albums = await Album . find ( { } ) . lean ( ) . select ( "-__v" ) . select ( "-_id" ) ;
4332
44- for ( const album of albums ) {
45- const songPromises = album . tracks . map ( ( songId ) =>
46- Song . findById ( songId . toString ( ) ) . select ( "-__v" ) . select ( "-_id" ) . lean ( )
47- ) ;
48- const songs = await Promise . all ( songPromises ) ;
49-
50- album . tracks = cleanUpSongs ( songs , album ) ;
51- album . songs = album . tracks . length ;
33+ for ( let album of albums ) {
34+ album = await enhanceAlbumWithSongsData ( album ) ;
5235 }
5336
5437 return res . json ( albums ) ;
@@ -66,19 +49,13 @@ const searchAlbum = async (req, res) => {
6649 . select ( "-__v -_id" )
6750 . lean ( ) ;
6851
69- for ( const album of albums ) {
70- const songPromises = album . tracks . map ( ( songId ) =>
71- Song . findById ( songId . toString ( ) ) . select ( "-__v" ) . select ( "-_id" ) . lean ( )
72- ) ;
73- const songs = await Promise . all ( songPromises ) ;
74-
75- album . tracks = cleanUpSongs ( songs , album ) ;
76- album . songs = album . tracks . length ;
52+ for ( let album of albums ) {
53+ album = await enhanceAlbumWithSongsData ( album ) ;
7754 }
7855
7956 res . json ( albums ) ;
8057 } catch ( error ) {
81- console . error ( "Error searching songs :" , error . message ) ;
58+ console . error ( "Error searching albums :" , error . message ) ;
8259 res . status ( 500 ) . json ( { error : "Internal Server Error" } ) ;
8360 }
8461} ;
0 commit comments