You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

79 lines
2.4 KiB

const models = require('../models');
import * as api from '../../client/src/api';
import { EndpointError, EndpointHandler } from './types';
export const CreateSongEndpointHandler:EndpointHandler = async (req: any, res: any) => {
if (!api.checkCreateSongRequest(req)) {
const e:EndpointError = {
internalMessage: 'Invalid CreateSong request: ' + JSON.stringify(req.body),
httpStatus: 400
};
throw e;
}
const reqObject: api.CreateSongRequest = req.body;
// 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: artistId }
})
.then((artist: any[]) => {
if (artist.length != 1) {
const e:EndpointError = {
internalMessage: 'There is no artist with id ' + artistId + '.',
httpStatus: 400
};
throw e;
}
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) {
const e:EndpointError = {
internalMessage: 'There is no album with id ' + albumId + '.',
httpStatus: 400
};
throw e;
}
return album[0];
})
);
});
var albumInstancesPromise = Promise.all(albumInstancePromises);
// Upon finish retrieving artists and albums, create the song and associate it.
await 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);
})
});
}