|
|
|
@ -8,27 +8,61 @@ export const CreateSongEndpointHandler = (req: any, res: any) => { |
|
|
|
|
return; |
|
|
|
|
} |
|
|
|
|
const reqObject: api.CreateSongRequest = req.body; |
|
|
|
|
console.log("Request create song: ", reqObject); // TODO: remove
|
|
|
|
|
// First check that the artist exists.
|
|
|
|
|
|
|
|
|
|
// Start retrieving the artist instances to link the song to.
|
|
|
|
|
var artistInstancePromises: Promise<any>[] = []; |
|
|
|
|
reqObject.artistIds?.forEach((artistId: Number) => { |
|
|
|
|
artistInstancePromises.push( |
|
|
|
|
models.Artist.findAll({ |
|
|
|
|
where: { id: reqObject.artistId } |
|
|
|
|
where: { id: artistId } |
|
|
|
|
}) |
|
|
|
|
.then((artist: any[]) => { |
|
|
|
|
if (artist.length != 1) { |
|
|
|
|
console.log('Invalid CreateSong request: ' + JSON.stringify(req.body) |
|
|
|
|
+ ". There is no artist with id " + reqObject.artistId + "."); |
|
|
|
|
res.sendStatus(400); |
|
|
|
|
return; |
|
|
|
|
throw 'There is no artist with id ' + artistId + '.'; |
|
|
|
|
} |
|
|
|
|
return artist[0]; |
|
|
|
|
}) |
|
|
|
|
); |
|
|
|
|
}); |
|
|
|
|
var artistInstancesPromise = Promise.all(artistInstancePromises); |
|
|
|
|
|
|
|
|
|
// Start retrieving the album instances to link the song to.
|
|
|
|
|
var albumInstancePromises: Promise<any>[] = []; |
|
|
|
|
reqObject.albumIds?.forEach((albumId: Number) => { |
|
|
|
|
albumInstancePromises.push( |
|
|
|
|
models.Album.findAll({ |
|
|
|
|
where: { id: albumId } |
|
|
|
|
}) |
|
|
|
|
.then((album: any[]) => { |
|
|
|
|
if (album.length != 1) { |
|
|
|
|
throw 'There is no album with id ' + albumId + '.'; |
|
|
|
|
} |
|
|
|
|
return album[0]; |
|
|
|
|
}) |
|
|
|
|
); |
|
|
|
|
}); |
|
|
|
|
var albumInstancesPromise = Promise.all(albumInstancePromises); |
|
|
|
|
|
|
|
|
|
// Upon finish retrieving artists and albums, create the song and associate it.
|
|
|
|
|
Promise.all([artistInstancesPromise, albumInstancesPromise]) |
|
|
|
|
.then((values: any) => { |
|
|
|
|
var [artists, albums] = values; |
|
|
|
|
models.Song.create({ |
|
|
|
|
title: reqObject.title, |
|
|
|
|
ArtistId: reqObject.artistId |
|
|
|
|
}) |
|
|
|
|
.then(Promise.all([ |
|
|
|
|
(song: any) => { |
|
|
|
|
song.addArtists(artists); |
|
|
|
|
}, |
|
|
|
|
(song: any) => { |
|
|
|
|
song.addAlbums(albums); |
|
|
|
|
} |
|
|
|
|
])) |
|
|
|
|
.then((song: any) => { |
|
|
|
|
const responseObject: api.CreateSongResponse = { |
|
|
|
|
id: song.id |
|
|
|
|
}; |
|
|
|
|
res.status(200).send(responseObject); |
|
|
|
|
}) |
|
|
|
|
}) |
|
|
|
|
}); |
|
|
|
|
} |