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.
86 lines
3.1 KiB
86 lines
3.1 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: reqObject.id } |
|
}) |
|
.then((song: any[]) => { |
|
if (song.length != 1) { |
|
const e: EndpointError = { |
|
internalMessage: 'There is no song with id ' + reqObject.id + '.', |
|
httpStatus: 400 |
|
}; |
|
throw e; |
|
} |
|
return song[0]; |
|
}); |
|
|
|
// Upon finish retrieving artists and albums, create the song and associate it. |
|
await Promise.all([artistInstancesPromise, albumInstancesPromise, songInstancePromise]) |
|
.then(async (values: any) => { |
|
var [artists, albums, song] = values; |
|
song.setArtists(artists); |
|
song.setAlbums(albums); |
|
song.setTitle(reqObject.title); |
|
await song.save(); |
|
}) |
|
.then(() => { |
|
res.status(200).send({}); |
|
}) |
|
.catch(catchUnhandledErrors); |
|
} |