const models = require('../models'); import * as api from '../../client/src/api'; import { EndpointError, EndpointHandler, catchUnhandledErrors } from './types'; export const CreateTagEndpointHandler: EndpointHandler = async (req: any, res: any) => { if (!api.checkCreateTagRequest(req)) { const e: EndpointError = { internalMessage: 'Invalid CreateTag request: ' + JSON.stringify(req.body), httpStatus: 400 }; throw e; } const reqObject: api.CreateTagRequest = 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 })(); (async () => { const maybeParent = await maybeNewParentPromise; const tag = await models.Tag.create({ name: reqObject.name }); reqObject.parentId && await tag.setParent(maybeParent); await tag.save(); const responseObject: api.CreateTagResponse = { id: tag.id }; res.status(200).send(responseObject); })() .catch(catchUnhandledErrors); }