import * as api from '../../client/src/api'; import { EndpointError, EndpointHandler, catchUnhandledErrors } from './types'; import Knex from 'knex'; export const CreateAlbumEndpointHandler: EndpointHandler = async (req: any, res: any, knex: Knex) => { if (!api.checkCreateAlbumRequest(req)) { const e: EndpointError = { internalMessage: 'Invalid CreateAlbum request: ' + JSON.stringify(req.body), httpStatus: 400 }; throw e; } const reqObject: api.CreateAlbumRequest = req.body; console.log("Create Album:", reqObject); await knex.transaction(async (trx) => { try { // Start retrieving artists. const artistIdsPromise = reqObject.artistIds ? trx.select('id') .from('artists') .whereIn('id', reqObject.artistIds) .then((as: any) => as.map((a: any) => a['id'])) : (async () => { return [] })(); // Start retrieving tags. const tagIdsPromise = reqObject.tagIds ? trx.select('id') .from('tags') .whereIn('id', reqObject.tagIds) .then((as: any) => as.map((a: any) => a['id'])) : (async () => { return [] })(); // Wait for the requests to finish. var [artists, tags] = await Promise.all([artistIdsPromise, tagIdsPromise]);; // Check that we found all artists and tags we need. if ((reqObject.artistIds && artists.length !== reqObject.artistIds.length) || (reqObject.tagIds && tags.length !== reqObject.tagIds.length)) { const e: EndpointError = { internalMessage: 'Not all albums and/or artists and/or tags exist for CreateAlbum request: ' + JSON.stringify(req.body), httpStatus: 400 }; throw e; } // Create the album. const albumId = (await trx('albums') .insert({ name: reqObject.name, storeLinks: JSON.stringify(reqObject.storeLinks || []), }) )[0]; // Link the artists via the linking table. if (artists && artists.length) { await trx('artists_albums').insert( artists.map((artistId: number) => { return { artistId: artistId, albumId: albumId, } }) ) } // Link the tags via the linking table. if (tags && tags.length) { await trx('albums_tags').insert( tags.map((tagId: number) => { return { albumId: albumId, tagId: tagId, } }) ) } // Respond to the request. const responseObject: api.CreateSongResponse = { id: albumId }; res.status(200).send(responseObject); } catch (e) { catchUnhandledErrors(e); trx.rollback(); } }) }