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.
 
 
 
 

74 lines
2.3 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
}
}
});
// Start retrieving the tag instances to link the song to.
var tagInstancesPromise = reqObject.tagIds && models.Tag.findAll({
where: {
id: {
[Op.in]: reqObject.tagIds
}
}
});
// Upon finish retrieving dependents, create the song and associate it.
await Promise.all([artistInstancesPromise, albumInstancesPromise, tagInstancesPromise])
.then((values: any) => {
var [artists, albums, tags] = values;
if ((reqObject.artistIds && artists.length !== reqObject.artistIds.length) ||
(reqObject.albumIds && albums.length !== reqObject.albumIds.length) ||
(reqObject.tagIds && tags.length !== reqObject.tagIds.length)) {
const e: EndpointError = {
internalMessage: 'Not all albums and/or artists and/or tags 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);
tags && song.addTags(tags);
return song.save();
})
.then((song: any) => {
const responseObject: api.CreateSongResponse = {
id: song.id
};
res.status(200).send(responseObject);
})
.catch(catchUnhandledErrors);
}