const models = require('../models'); import * as api from '../../client/src/api'; import { EndpointError, EndpointHandler, catchUnhandledErrors } from './types'; import tag from '../models/tag'; export const ModifyTagEndpointHandler: EndpointHandler = async (req: any, res: any) => { if (!api.checkModifySongRequest(req)) { const e: EndpointError = { internalMessage: 'Invalid ModifyTag request: ' + JSON.stringify(req.body), httpStatus: 400 }; throw e; } const reqObject: api.ModifyTagRequest = req.body; const getTag = async (id:Number) => { const tag = await models.Tag.findAll({ where: { id: id } }); if(tag.length != 1) { const e: EndpointError = { internalMessage: 'There is no tag with id ' + id + '.', httpStatus: 400 }; throw e; } return tag[0]; } // If applicable, start retrieving the new parent tag. const maybeNewParentPromise:Promise|Promise = (reqObject.parentId) ? getTag(reqObject.parentId) : (async () => { return undefined })(); // Start retrieving the tag to modify. var tagInstancePromise: Promise = getTag(req.params.id); // Upon finish retrieving artists and albums, modify the song. await Promise.all([maybeNewParentPromise, tagInstancePromise]) .then(async (values: any) => { var [maybeParent, tag] = values; if(reqObject.name) { tag.setName(reqObject.name) }; if(reqObject.parentId) { tag.setParent(maybeParent) }; await tag.save(); }) .then(() => { res.status(200).send({}); }) .catch(catchUnhandledErrors); }