11const Song = require ( "../models/Song" ) ;
22const Album = require ( "../models/Album" ) ;
3- const { isAdmin } = require ( "../utils" ) ;
3+ const { isAdmin, getAlbumDetails } = require ( "../utils" ) ;
44
55const getSong = async ( req , res ) => {
66 try {
77 const { name } = req . params ;
8- const song = await Song . findOne ( { name } )
8+ const song = await Song . findOne ( { name : { $regex : name , $options : "i" } } )
99 . select ( "-__v -_id" ) // Exclude unnecessary fields
1010 . lean ( ) ;
1111
@@ -14,29 +14,19 @@ const getSong = async (req, res) => {
1414 }
1515
1616 // Get album details without the tracks property
17- const album = await Album . findById ( song . albumId )
18- . select ( "-__v -_id" ) // Exclude unnecessary fields
19- . lean ( ) ;
17+ const albumDetails = await getAlbumDetails ( song . albumId ) ;
2018
21- if ( ! album ) {
19+ if ( ! albumDetails ) {
2220 return res . status ( 404 ) . json ( { error : "Album not found" } ) ;
2321 }
2422
25- const albumDetails = {
26- title : album . title ,
27- albumCover : album . albumCover ,
28- artist : album . artist ,
29- releaseYear : album . releaseYear ,
30- releaseDate : album . realeaseDate ,
31- } ;
32-
3323 res . json ( {
3424 ...song ,
3525 album : albumDetails ,
3626 } ) ;
3727 } catch ( error ) {
38- console . error ( "Error fetching song:" , error . message ) ;
39- res . status ( 500 ) . json ( { error : "Internal Server Error" } ) ;
28+ console . error ( "Error fetching songs" ) ;
29+ errorHandler ( res , error ) ;
4030 }
4131} ;
4232
@@ -45,19 +35,22 @@ const getAllSongs = async (req, res) => {
4535 const songs = await Song . find ( ) . select ( "-__v -_id" ) . lean ( ) ;
4636
4737 for ( const song of songs ) {
48- const album = await Album . findById ( song . albumId )
49- . select ( "-__v -_id" )
50- . lean ( ) ;
38+ // Use getAlbumDetails to get album details from albumId
39+ const albumDetails = await getAlbumDetails ( song . albumId ) ;
5140
52- if ( album ) {
53- song . albumName = album . title ;
41+ if ( albumDetails ) {
42+ song . albumName = albumDetails . albumName ;
5443 delete song . albumId ; // Remove the original albumId field
5544 }
5645 }
5746
5847 res . json ( songs ) ;
5948 } catch ( error ) {
60- console . error ( "Error fetching songs:" , error . message ) ;
49+ console . error ( "Error fetching songs" ) ;
50+ errorHandler ( res , error ) ;
51+ }
52+ } ;
53+
6154 res . status ( 500 ) . json ( { error : "Internal Server Error" } ) ;
6255 }
6356} ;
@@ -95,8 +88,8 @@ const newSong = async (req, res) => {
9588
9689 res . json ( savedSongs ) ;
9790 } catch ( error ) {
98- console . error ( "Error creating songs and updating album:" , error . message ) ;
99- res . status ( 500 ) . json ( { error : "Internal Server Error" } ) ;
91+ console . error ( "Error creating a song and updating an album" ) ;
92+ errorHandler ( res , error ) ;
10093 }
10194} ;
10295
0 commit comments