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.
 
 
 
 

87 lines
3.3 KiB

const models = require('../models');
import * as api from '../../client/src/api';
import { EndpointError, EndpointHandler, catchUnhandledErrors } from './types';
export const ModifySongEndpointHandler: EndpointHandler = async (req: any, res: any) => {
if (!api.checkModifySongRequest(req)) {
const e: EndpointError = {
internalMessage: 'Invalid ModifySong request: ' + JSON.stringify(req.body),
httpStatus: 400
};
throw e;
}
const reqObject: api.ModifySongRequest = 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);
// Start retrieving the song to modify.
var songInstancePromise: Promise<any> =
models.Song.findAll({
where: { id: req.params.id }
})
.then((song: any[]) => {
if (song.length != 1) {
const e: EndpointError = {
internalMessage: 'There is no song with id ' + req.params.id + '.',
httpStatus: 400
};
throw e;
}
return song[0];
});
// Upon finish retrieving artists and albums, modify the song.
await Promise.all([artistInstancesPromise, albumInstancesPromise, songInstancePromise])
.then(async (values: any) => {
var [artists, albums, song] = values;
if(reqObject.artistIds) { song.setArtists(artists) };
if(reqObject.albumIds) { song.setAlbums(albums) };
if(reqObject.title) { song.setTitle(reqObject.title) };
if(reqObject.storeLinks) { song.setStoreIds(reqObject.storeLinks) };
await song.save();
})
.then(() => {
res.status(200).send({});
})
.catch(catchUnhandledErrors);
}