import * as api from '../../client/src/api/api'; import { EndpointError, EndpointHandler, handleErrorsInEndpoint } from './types'; import Knex from 'knex'; import asJson from '../lib/asJson'; import { createTrack, deleteTrack, getTrack, modifyTrack } from '../db/Track'; export const PostTrack: EndpointHandler = async (req: any, res: any, knex: Knex) => { if (!api.checkPostTrackRequest(req.body)) { const e: EndpointError = { name: "EndpointError", message: 'Invalid PostTrack request', httpStatus: 400 }; throw e; } const reqObject: api.PostTrackRequest = req.body; const { id: userId } = req.user; console.log("User ", userId, ": Post Track ", reqObject); try { let id = await createTrack(userId, reqObject, knex); res.status(200).send({ id: id, }); } catch (e) { handleErrorsInEndpoint(e); } } export const GetTrack: EndpointHandler = async (req: any, res: any, knex: Knex) => { const { id: userId } = req.user; try { let track = await getTrack(req.params.id, userId, knex); await res.status(200).send(track); } catch (e) { handleErrorsInEndpoint(e) } } export const PutTrack: EndpointHandler = async (req: any, res: any, knex: Knex) => { if (!api.checkPutTrackRequest(req.body)) { const e: EndpointError = { name: "EndpointError", message: 'Invalid PutTrack request', httpStatus: 400 }; throw e; } const reqObject: api.PutTrackRequest = req.body; const { id: userId } = req.user; console.log("User ", userId, ": Put Track ", reqObject); try { modifyTrack(userId, req.params.id, reqObject, knex); res.status(200).send(); } catch (e) { handleErrorsInEndpoint(e); } } export const PatchTrack: EndpointHandler = async (req: any, res: any, knex: Knex) => { if (!api.checkPatchTrackRequest(req.body)) { const e: EndpointError = { name: "EndpointError", message: 'Invalid PatchTrack request', httpStatus: 400 }; throw e; } const reqObject: api.PatchTrackRequest = req.body; const { id: userId } = req.user; console.log("User ", userId, ": Patch Track ", reqObject); try { modifyTrack(userId, req.params.id, reqObject, knex); res.status(200).send(); } catch (e) { handleErrorsInEndpoint(e); } } export const DeleteTrack: EndpointHandler = async (req: any, res: any, knex: Knex) => { const { id: userId } = req.user; console.log("User ", userId, ": Delete Track ", req.params.id); try { await deleteTrack(userId, req.params.id, knex); res.status(200).send(); } catch (e) { handleErrorsInEndpoint(e); } } export const trackEndpoints: [ string, string, boolean, EndpointHandler ][] = [ [ api.PostTrackEndpoint, 'post', true, PostTrack ], [ api.GetTrackEndpoint, 'get', true, GetTrack ], [ api.PutTrackEndpoint, 'put', true, PutTrack ], [ api.PatchTrackEndpoint, 'patch', true, PatchTrack ], [ api.DeleteTrackEndpoint, 'delete', true, DeleteTrack ], ];