const models = require('../models'); import * as api from '../../client/src/api'; export const CreateSongEndpointHandler = (req: any, res: any) => { if (!api.checkCreateSongRequest(req)) { console.log('Invalid CreateSong request: ' + JSON.stringify(req.body)); res.sendStatus(400); return; } const reqObject: api.CreateSongRequest = req.body; // Start retrieving the artist instances to link the song to. var artistInstancePromises: Promise[] = []; reqObject.artistIds?.forEach((artistId: Number) => { artistInstancePromises.push( models.Artist.findAll({ where: { id: artistId } }) .then((artist: any[]) => { if (artist.length != 1) { 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[] = []; 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, }) .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); }) }); }