const models = require('../models'); import * as api from '../../client/src/api'; import { EndpointError, EndpointHandler, catchUnhandledErrors } from './types'; const { Op } = require("sequelize"); export const CreateArtistEndpointHandler: EndpointHandler = async (req: any, res: any) => { if (!api.checkCreateArtistRequest(req)) { const e: EndpointError = { internalMessage: 'Invalid CreateArtist request: ' + JSON.stringify(req.body), httpStatus: 400 }; throw e; } const reqObject: api.CreateArtistRequest = req.body; // Start retrieving the tag instances to link the artist to. var tagInstancesPromise = reqObject.tagIds && models.Tag.findAll({ where: { id: { [Op.in]: reqObject.tagIds } } }); // Upon finish retrieving artists and albums, create the artist and associate it. await Promise.all([tagInstancesPromise]) .then((values: any) => { var [tags] = values; if (reqObject.tagIds && tags.length !== reqObject.tagIds.length) { const e: EndpointError = { internalMessage: 'Not all atags exist for CreateArtist request: ' + JSON.stringify(req.body), httpStatus: 400 }; throw e; } var artist = models.Artist.build({ name: reqObject.name, storeLinks: reqObject.storeLinks || [], }); tags && artist.addTags(tags); return artist.save(); }) .then((artist: any) => { const responseObject: api.CreateSongResponse = { id: artist.id }; res.status(200).send(responseObject); }) .catch(catchUnhandledErrors); }