Files
adastra_api/src/routes/api/skydive/jumps.routes.js
T
julien da1f9437ab feat(tests): add Jest+Supertest infrastructure with jump route suite (14 tests)
- Extract Express app creation into src/createApp.js to enable testing without starting the server
- Add Jest, Supertest, test helpers (createTestApp, auth token generator)
- Write 14 integration tests for skydive/jumps: auth protection, CRUD, ownership checks

Bugs caught and fixed by the test suite:
- MongoDB models: author field typed as Schema.Types.UUID (Mongoose 6 rejects string UUIDs) → changed to String
- Jump.toJSONFor: called toProfileJSONFor on a UUID string → guarded with typeof check
- exceptions.handler: used err.statusCode but express-jwt throws err.status → returns 500 on 401 errors
- Jump.count(query): deprecated Mongoose method was ignoring the filter → replaced with countDocuments
- jumps.routes GET /: $or query included non-schema field "title" stripped by strictQuery, leaving {} (match-all) → replaced with slug/lieu search
- $regex: was passing a JS RegExp object which serializes to {} in MongoDB → now passes raw string
2026-04-26 01:23:01 +02:00

520 lines
19 KiB
JavaScript

var router = require('express').Router(),
mongoose = require('mongoose'),
Jump = mongoose.model('Jump'),
JumpFile = mongoose.model('JumpFile'),
X2DataLog = mongoose.model('X2DataLog');
const auth = require('../../../middlewares/auth'),
chalk = require('chalk'),
queries = require('../../queries');
const DateUtilities = require('../../../utils/dateUtilities');
const utils = require('../../../utils');
const { UserService } = require('../../../services');
// Preload jump objects on routes with ':jump'
router.param('jump', function (req, res, next, slug) {
Jump.findOne({ slug: slug })
.populate('author')
.populate('files')
.populate('x2data')
.then(function (jump) {
if (!jump) {
return res.sendStatus(404);
}
req.jump = jump;
return next();
}).catch(next);
});
/**
* return all jumps
*/
router.get('/', auth.required, function (req, res, next) {
let query = {};
let limit = 25;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
if (typeof req.query.title !== 'undefined') {
query = {
$or: [
{ slug: { $regex: req.query.title, $options: 'i' } },
{ lieu: { $regex: req.query.title, $options: 'i' } },
],
};
}
if (typeof req.query.numeroRangeStart !== 'undefined' && typeof req.query.numeroRangeEnd !== 'undefined') {
query.numero = {
$gte: req.query.numeroRangeStart,
$lte: req.query.numeroRangeEnd
};
}
if (typeof req.query.tailleRangeStart !== 'undefined' && typeof req.query.tailleRangeEnd !== 'undefined') {
query.taille = {
$gte: req.query.tailleRangeStart,
$lte: req.query.tailleRangeEnd
};
}
if (typeof req.query.participantsRangeStart !== 'undefined' && typeof req.query.participantsRangeEnd !== 'undefined') {
query.participants = {
$gte: req.query.participantsRangeStart,
$lte: req.query.participantsRangeEnd
};
}
if (typeof req.query.hauteurRangeStart !== 'undefined' && typeof req.query.hauteurRangeEnd !== 'undefined') {
query.hauteur = {
$gte: req.query.hauteurRangeStart,
$lte: req.query.hauteurRangeEnd
};
}
if (typeof req.query.yearRangeStart !== 'undefined' && typeof req.query.yearRangeEnd !== 'undefined') {
query.date = {
$gte: new Date(`${req.query.yearRangeStart}-01-01 00:00:00`),
$lte: new Date(`${req.query.yearRangeEnd}-12-31 23:59:59`)
};
}
if (typeof req.query.dateRangeStart !== 'undefined' && typeof req.query.dateRangeEnd !== 'undefined') {
query.date = {
$gte: new Date(`${req.query.dateRangeStart} 00:00:00`),
$lte: new Date(`${req.query.dateRangeEnd} 23:59:59`)
};
}
Promise.all([
req.query.author ? UserService.getUserByUsername(req.query.author) : null,
req.query.favorited ? UserService.getUserByUsername(req.query.favorited) : null
]).then(function (users) {
let author = users[0];
if (author) {
query.author = author.id;
}
Promise.all([
Jump.find(query)
.skip(Number(offset))
.limit(Number(limit))
.sort({ numero: 'desc' })
.populate('author')
.populate('files')
.populate('x2data')
.exec(),
Jump.countDocuments(query).exec(),
req.payload ? UserService.getUserById(req.payload.id) : null
]).then(function (results) {
let jumps = results[0];
let jumpsCount = results[1];
return res.json({
jumps: jumps.map(function (jump) {
return jump.toJSONFor(null);
}),
jumpsCount: jumpsCount
});
});
}).catch(next);
});
router.get('/allByCategorie', auth.required, function (req, res, next) {
UserService.getUserById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
let limit = 120;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
let query = queries.getJumpsByCategoryQuery(user.id);
Jump.aggregate(query)
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
let jumps = result.map(function (data) {
return { categorie: data._id.categorie, count: data.count };
});
return res.json({
jumps: jumps,
jumpsCount: jumps.length
});
}).catch(next);
}).catch(next);
});
router.get('/allByDate', auth.required, function (req, res, next) {
UserService.getUserById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
let limit = 120;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
let query = queries.getJumpsByDateQuery(user.id);
Jump.aggregate(query)
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
let jumps = result.map(function (data) {
return { year: data._id.year, month: data._id.month, count: data.count };
});
return res.json({
jumps: jumps,
jumpsCount: jumps.length
});
}).catch(next);
}).catch(next);
});
router.get('/allByDay', auth.required, function (req, res, next) {
UserService.getUserById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
let query = {};
let limit = 50;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
if (typeof req.query.dateRangeStart !== 'undefined' && typeof req.query.dateRangeEnd !== 'undefined') {
query = queries.getJumpsByDayQuery(
user.id,
req.query.dateRangeStart,
req.query.dateRangeEnd
);
} else {
query = queries.getJumpsByDayQuery(user.id);
}
Jump.aggregate(query)
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
let days = result.map(function (data) {
return { jumps: data.jumps, count: data.count };
});
return res.json({
days: days,
daysCount: days.length
});
}).catch(next);
}).catch(next);
});
router.get('/allByModule', auth.required, function (req, res, next) {
UserService.getUserById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
let limit = 120;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
let query = queries.getJumpsByModuleQuery(user.id);
Jump.aggregate(query)
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
let jumps = result.map(function (data) {
return { categorie: data._id.categorie, module: data._id.module, count: data.count };
});
return res.json({
jumps: jumps,
jumpsCount: jumps.length
});
}).catch(next);
}).catch(next);
});
/**
* return a jump from SkydiverId API
*/
router.get('/allFromSkydiverIdApi', auth.required, function (req, res, next) {
UserService.getUserById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
utils.fetchSkydiverIdApi('jumps', req.query).then(result => {
if (result.errors === undefined) {
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.green(`Réception des sauts SkydiverId`));
} else {
console.log(`${DateUtilities.getDateTimeISOString()}`, chalk.red(`Une erreur ${result.errors.code} '${result.errors.type}' est survenue lors de la réception des sauts SkydiverId : ${result.errors.name} ${result.errors.message}`));
}
return res.json({
jumps: result,
jumpsCount: result.items.length
});
}).catch(next);
}).catch(next);
});
/**
* return last jump
*/
router.get('/last', auth.required, function (req, res, next) {
UserService.getUserById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
Jump.find({author: user.id})
.limit(1)
.sort({ numero: 'desc' })
.populate('author')
.populate('files')
.populate('x2data')
.exec()
.then(function (jumps) {
if (!jumps || jumps.length === 0) {
return res.status(404).json({ errors: { "Not Found": "aucun saut trouvé" } });
}
req.lastjump = jumps[0];
if (req.lastjump.author.username !== req.payload.username) {
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
return res.json({ jump: req.lastjump.toJSONFor(null) });
}).catch(next);
}).catch(next);
});
/**
* return a jump
*/
router.get('/:jump', auth.required, function (req, res, next) {
UserService.getUserById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
const authorId = req.jump.author?.id ?? req.jump.author?.toString();
if (authorId !== req.payload.id) {
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
Promise.all([
Jump.findOne({numero: (req.jump.numero - 1)}).exec(),
Jump.findOne({numero: (req.jump.numero + 1)}).exec(),
]).then(function (results) {
return res.json({
jump: req.jump.toJSONFor(null),
prevJump: results[0],
nextJump: results[1]
});
}).catch(next);
}).catch(next);
});
/**
* save a jump
*/
router.post('/', auth.required, function (req, res, next) {
UserService.getUserById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
let jump = new Jump(req.body.jump);
jump.author = user.id;
return jump.save().then(function () {
return res.json({ jump: jump.toJSONFor(null) });
});
}).catch(next);
});
/**
* save jump data file
*/
router.post('/data/:jump', auth.required, function (req, res, next) {
UserService.getUserById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
const authorId = req.jump.author?.id ?? req.jump.author?.toString();
if (authorId !== req.payload.id) {
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
Object.assign(req.body.file, {_id: new mongoose.Types.ObjectId()});
let file = new JumpFile(req.body.file);
let files = req.jump.files ? req.jump.files : [];
file.author = user.id;
files.push(file);
return file.save().then(function () {
Object.assign(req.body.data, {_id: new mongoose.Types.ObjectId()});
let x2data = new X2DataLog(req.body.data);
x2data.author = user.id;
return x2data.save().then(function () {
req.jump.files = files;
req.jump.x2data = x2data;
Jump.updateOne({_id: req.jump._id}, {files: files, x2data: x2data._id}).then(function () {
return res.json({ jump: req.jump.toJSONFor(null) });
}).catch(next);
}).catch(next);
}).catch(next);
}).catch(next);
});
/**
* save a jump file
*/
router.post('/file/:jump', auth.required, function (req, res, next) {
UserService.getUserById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
const authorId = req.jump.author?.id ?? req.jump.author?.toString();
if (authorId !== req.payload.id) {
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
Object.assign(req.body.file, {_id: new mongoose.Types.ObjectId()});
let file = new JumpFile(req.body.file);
let files = req.jump.files ? req.jump.files : [];
file.author = user.id;
files.push(file);
return file.save().then(function () {
Jump.updateOne({_id: req.jump._id}, {files: files}).then(function () {
return res.json({ file: file.toJSONForJump() });
}).catch(next);
}).catch(next);
}).catch(next);
});
/**
* save a jump kml file
*/
router.post('/kml/:jump', auth.required, function (req, res, next) {
UserService.getUserById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
const authorId = req.jump.author?.id ?? req.jump.author?.toString();
if (authorId !== req.payload.id) {
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
Object.assign(req.body.file, {
_id: new mongoose.Types.ObjectId(),
name: `${req.jump.x2data.name}.kml`,
path: `/Volumes/Storage/Skydive/X2_Kmls/${req.jump.date.getFullYear()}/`,
type: 'kml'
});
let file = new JumpFile(req.body.file);
let files = req.jump.files ? req.jump.files : [];
file.author = user.id;
files.push(file);
return res.json({ file: file.toJSONForJump() });
}).catch(next);
});
/**
* update a jump
*/
router.put('/:jump', auth.required, function (req, res, next) {
UserService.getUserById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
const authorId = req.jump.author?.id ?? req.jump.author?.toString();
if (authorId !== req.payload.id) {
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
if (typeof req.body.jump.date !== 'undefined') {
req.jump.date = req.body.jump.date;
}
if (typeof req.body.jump.numero !== 'undefined') {
req.jump.numero = req.body.jump.numero;
}
if (typeof req.body.jump.lieu !== 'undefined') {
req.jump.lieu = req.body.jump.lieu;
}
if (typeof req.body.jump.oaci !== 'undefined') {
req.jump.oaci = req.body.jump.oaci;
}
if (typeof req.body.jump.aeronef !== 'undefined') {
req.jump.aeronef = req.body.jump.aeronef;
}
if (typeof req.body.jump.imat !== 'undefined') {
req.jump.imat = req.body.jump.imat;
}
if (typeof req.body.jump.hauteur !== 'undefined') {
req.jump.hauteur = req.body.jump.hauteur;
}
if (typeof req.body.jump.voile !== 'undefined') {
req.jump.voile = req.body.jump.voile;
}
if (typeof req.body.jump.taille !== 'undefined') {
req.jump.taille = req.body.jump.taille;
}
if (typeof req.body.jump.categorie !== 'undefined') {
req.jump.categorie = req.body.jump.categorie;
}
if (typeof req.body.jump.module !== 'undefined') {
req.jump.module = req.body.jump.module;
}
if (typeof req.body.jump.participants !== 'undefined') {
req.jump.participants = req.body.jump.participants;
}
if (typeof req.body.jump.sautants !== 'undefined') {
req.jump.sautants = req.body.jump.sautants;
}
if (typeof req.body.jump.programme !== 'undefined') {
req.jump.programme = req.body.jump.programme;
}
if (typeof req.body.jump.accessoires !== 'undefined') {
req.jump.accessoires = req.body.jump.accessoires;
}
if (typeof req.body.jump.zone !== 'undefined') {
req.jump.zone = req.body.jump.zone;
}
if (typeof req.body.jump.dossier !== 'undefined') {
req.jump.dossier = req.body.jump.dossier;
}
if (typeof req.body.jump.video !== 'undefined') {
req.jump.video = req.body.jump.video;
}
return req.jump.save().then(function (jump) {
return res.json({ jump: jump.toJSONFor(null) });
});
}).catch(next);
});
/**
* delete a jump
*/
router.delete('/:jump', auth.required, function (req, res, next) {
UserService.getUserById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
const authorId = req.jump.author?.id ?? req.jump.author?.toString();
if (authorId === req.payload.id) {
return req.jump.remove().then(function () {
return res.json({ deleted: true });
});
} else {
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
}).catch(next);
});
module.exports = router;