import * as api from '../../client/src/api'; import { EndpointError, EndpointHandler, catchUnhandledErrors } from './types'; import Knex from 'knex'; export const ModifySongEndpointHandler: EndpointHandler = async (req: any, res: any, knex: Knex) => { 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; console.log("Modify Song:", reqObject); await knex.transaction(async (trx) => { try { // Retrieve the song to be modified itself. const song = await trx.select('id') .from('songs') .where({ id: req.params.id }) .then((r: any) => (r && r[0]) ? r[0]['id'] : undefined) // Construct the new object from the original plus the // changes included in the PUT. const newSong = { ...song, ...reqObject, }; // Start retrieving artists. const artistIdsPromise = newSong.artistIds ? trx.select('artistId') .from('songs_artists') .whereIn('id', newSong.artistIds) .then((as: any) => as.map((a: any) => a['artistId'])) : (async () => { return undefined })(); // Start retrieving tags. const tagIdsPromise = newSong.tagIds ? trx.select('id') .from('songs_tags') .whereIn('id', newSong.tagIds) .then((ts: any) => ts.map((t: any) => t['tagId'])) : (async () => { return undefined })(); // Start retrieving albums. const albumIdsPromise = newSong.albumIds ? trx.select('id') .from('songs_albums') .whereIn('id', newSong.albumIds) .then((as: any) => as.map((a: any) => a['albumId'])) : (async () => { return undefined })(); // Wait for the requests to finish. var [artists, tags, albums] = await Promise.all([artistIdsPromise, tagIdsPromise, albumIdsPromise]);; // Check that we found all objects we need. if ((newSong.artistIds && artists.length !== newSong.artistIds.length) || (newSong.tagIds && tags.length !== newSong.tagIds.length) || (newSong.albumIds && albums.length !== newSong.albumIds.length) || !song) { const e: EndpointError = { internalMessage: 'Not all albums and/or artists and/or tags exist for ModifySong request: ' + JSON.stringify(req.body), httpStatus: 400 }; throw e; } // Modify the song. const modifySongPromise = trx('songs') .where({ 'id': req.params.id }) .update({ title: newSong.title, storeLinks: JSON.stringify(newSong.storeLinks || []), }) // Remove unlinked artists. // TODO: test this! const removeUnlinkedArtists = artists ? trx('songs_artists') .where({ 'songId': req.params.id }) .whereNotIn('artistId', newSong.artistIds || []) .delete() : undefined; // Remove unlinked tags. // TODO: test this! const removeUnlinkedTags = tags ? trx('songs_tags') .where({ 'songId': req.params.id }) .whereNotIn('tagId', newSong.tagIds || []) .delete() : undefined; // Remove unlinked albums. // TODO: test this! const removeUnlinkedAlbums = albums ? trx('songs_albums') .where({ 'songId': req.params.id }) .whereNotIn('albumId', newSong.albumIds || []) .delete() : undefined; // Link new artists. // TODO: test this! const addArtists = artists ? trx('songs_artists') .where({ 'songId': req.params.id }) .then((as: any) => as.map((a: any) => a['artistId'])) .then((doneArtistIds: number[]) => { // Get the set of artists that are not yet linked const toLink = artists.filter((id: number) => { return !doneArtistIds.includes(id); }); const insertObjects = toLink.map((artistId: number) => { return { artistId: artistId, songId: req.params.id, } }) // Link them return Promise.all( insertObjects.map((obj: any) => trx('songs_artists').insert(obj) ) ); }) : undefined; // Link new tags. // TODO: test this! const addTags = tags ? trx('songs_tags') .where({ 'songId': req.params.id }) .then((ts: any) => ts.map((t: any) => t['tagId'])) .then((doneTagIds: number[]) => { // Get the set of tags that are not yet linked const toLink = tags.filter((id: number) => { return !doneTagIds.includes(id); }); const insertObjects = toLink.map((tagId: number) => { return { tagId: tagId, songId: req.params.id, } }) // Link them return Promise.all( insertObjects.map((obj: any) => trx('songs_tags').insert(obj) ) ); }) : undefined; // Link new albums. // TODO: test this! const addAlbums = albums ? trx('songs_albums') .where({ 'albumId': req.params.id }) .then((as: any) => as.map((a: any) => a['albumId'])) .then((doneAlbumIds: number[]) => { // Get the set of albums that are not yet linked const toLink = albums.filter((id: number) => { return !doneAlbumIds.includes(id); }); const insertObjects = toLink.map((albumId: number) => { return { albumId: albumId, songId: req.params.id, } }) // Link them return Promise.all( insertObjects.map((obj: any) => trx('songs_albums').insert(obj) ) ); }) : undefined; // Wait for all operations to finish. await Promise.all([ modifySongPromise, removeUnlinkedArtists, removeUnlinkedTags, removeUnlinkedAlbums, addArtists, addTags, addAlbums, ]); // Respond to the request. res.status(200).send(); } catch (e) { catchUnhandledErrors(e); trx.rollback(); } }) }