Files
gymflow/server/src/routes/exercises.ts

122 lines
3.6 KiB
TypeScript

import express from 'express';
import jwt from 'jsonwebtoken';
import prisma from '../lib/prisma';
const router = express.Router();
const JWT_SECRET = process.env.JWT_SECRET || 'secret';
// Middleware to check auth
// Middleware to check auth
const authenticate = (req: any, res: any, next: any) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Unauthorized' });
try {
const decoded = jwt.verify(token, JWT_SECRET) as any;
req.user = decoded;
next();
} catch {
res.status(401).json({ error: 'Invalid token' });
}
};
router.use(authenticate);
// Get all exercises (system default + user custom)
router.get('/', async (req: any, res) => {
try {
const userId = req.user.userId;
const exercises = await prisma.exercise.findMany({
where: {
OR: [
{ userId: null }, // System default
{ userId } // User custom
]
}
});
res.json(exercises);
} catch (error) {
res.status(500).json({ error: 'Server error' });
}
});
// Get last set for specific exercise
router.get('/:id/last-set', async (req: any, res) => {
try {
const userId = req.user.userId;
const exerciseId = req.params.id;
const lastSet = await prisma.workoutSet.findFirst({
where: {
exerciseId,
session: { userId } // Ensure optimization by filtering sessions of the user
},
include: {
session: true
},
orderBy: {
timestamp: 'desc'
}
});
res.json({ success: true, set: lastSet });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Server error' });
}
});
// Create/Update exercise
router.post('/', async (req: any, res) => {
try {
const userId = req.user.userId;
const { id, name, type, bodyWeightPercentage, isArchived, isUnilateral } = req.body;
const data = {
name,
type,
bodyWeightPercentage: bodyWeightPercentage ? parseFloat(bodyWeightPercentage) : undefined,
isArchived: !!isArchived,
isUnilateral: !!isUnilateral
};
// If id exists and belongs to user, update. Else create.
// Note: We can't update system exercises directly. If user edits a system exercise,
// we should probably create a copy or handle it as a user override.
// For simplicity, let's assume we are creating/updating user exercises.
if (id) {
// Check if it exists and belongs to user
const existing = await prisma.exercise.findUnique({ where: { id } });
if (existing && existing.userId === userId) {
const updated = await prisma.exercise.update({
where: { id },
data: data
});
return res.json(updated);
}
}
// Create new
const newExercise = await prisma.exercise.create({
data: {
id: id || undefined, // Use provided ID if available
userId,
name: data.name,
type: data.type,
bodyWeightPercentage: data.bodyWeightPercentage,
isArchived: data.isArchived,
isUnilateral: data.isUnilateral,
}
});
res.json(newExercise);
} catch (error) {
res.status(500).json({ error: 'Server error' });
}
});
export default router;