59 lines
2.1 KiB
JavaScript
59 lines
2.1 KiB
JavaScript
'use strict';
|
|
|
|
const express = require('express');
|
|
const { models } = require('../../core/db');
|
|
const { authenticateToken, authenticateRole } = require('../../core/auth');
|
|
const { ok, created, collection, noContent } = require('../../core/respond');
|
|
const { AppError } = require('../../core/errors');
|
|
const { createCrossfitWorkout: createCrossfitSchema } = require('../../core/schemas/crossfit');
|
|
const svc = require('./service');
|
|
|
|
const router = express.Router();
|
|
router.prefix = 'crossfit-workouts';
|
|
|
|
const COACH_PLUS = ['Owner', 'Coach', 'SystemAdmin'];
|
|
const OWNERS = ['Owner', 'SystemAdmin'];
|
|
|
|
function validate(schema) {
|
|
return (req, res, next) => {
|
|
const result = schema.safeParse(req.body);
|
|
if (!result.success) {
|
|
const e = result.error.errors[0];
|
|
return next(new AppError('VALIDATION_FAILED', e.message, 400, e.path[0]));
|
|
}
|
|
req.body = result.data;
|
|
next();
|
|
};
|
|
}
|
|
|
|
router.get('/', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => {
|
|
try {
|
|
const { page = 1, limit = 20 } = req.query;
|
|
const { rows, count } = await svc.getCrossfitWorkouts(models, req.user.organizationId, { page: +page, limit: +limit });
|
|
collection(res, rows, count, +page, +limit);
|
|
} catch (err) { next(err); }
|
|
});
|
|
|
|
router.post('/', authenticateToken, authenticateRole(COACH_PLUS), validate(createCrossfitSchema), async (req, res, next) => {
|
|
try {
|
|
const workout = await svc.createCrossfitWorkout(models, req, req.user.organizationId, req.body);
|
|
created(res, workout);
|
|
} catch (err) { next(err); }
|
|
});
|
|
|
|
router.get('/:id', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => {
|
|
try {
|
|
const workout = await svc.getCrossfitWorkoutById(models, parseInt(req.params.id, 10), req.user.organizationId);
|
|
ok(res, workout);
|
|
} catch (err) { next(err); }
|
|
});
|
|
|
|
router.delete('/:id', authenticateToken, authenticateRole(OWNERS), async (req, res, next) => {
|
|
try {
|
|
await svc.deleteCrossfitWorkout(models, req, parseInt(req.params.id, 10), req.user.organizationId);
|
|
noContent(res);
|
|
} catch (err) { next(err); }
|
|
});
|
|
|
|
module.exports = router;
|