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.
63 lines
2.0 KiB
63 lines
2.0 KiB
const models = require('../models'); |
|
import * as api from '../../client/src/api'; |
|
import { EndpointError, EndpointHandler, catchUnhandledErrors } from './types'; |
|
const { Op } = require("sequelize"); |
|
|
|
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 artistInstancesPromise = reqObject.artistIds && models.Artist.findAll({ |
|
where: { |
|
id: { |
|
[Op.in]: reqObject.artistIds |
|
} |
|
} |
|
}); |
|
|
|
// Start retrieving the album instances to link the song to. |
|
var albumInstancesPromise = reqObject.albumIds && models.Album.findAll({ |
|
where: { |
|
id: { |
|
[Op.in]: reqObject.albumIds |
|
} |
|
} |
|
}); |
|
|
|
// Upon finish retrieving artists and albums, create the song and associate it. |
|
await Promise.all([artistInstancesPromise, albumInstancesPromise]) |
|
.then((values: any) => { |
|
var [artists, albums] = values; |
|
|
|
if ((reqObject.artistIds && artists.length !== reqObject.artistIds.length) || |
|
(reqObject.albumIds && albums.length !== reqObject.albumIds.length)) { |
|
const e: EndpointError = { |
|
internalMessage: 'Not all albums and/or artists exist for CreateSong request: ' + JSON.stringify(req.body), |
|
httpStatus: 400 |
|
}; |
|
throw e; |
|
} |
|
|
|
var song = models.Song.build({ |
|
title: reqObject.title, |
|
storeLinks: reqObject.storeLinks || [], |
|
}); |
|
artists && song.addArtists(artists); |
|
albums && song.addAlbums(albums); |
|
return song.save(); |
|
}) |
|
.then((song: any) => { |
|
const responseObject: api.CreateSongResponse = { |
|
id: song.id |
|
}; |
|
res.status(200).send(responseObject); |
|
}) |
|
.catch(catchUnhandledErrors); |
|
} |