Implémentation SkydiverId API

This commit is contained in:
Rampeur
2024-05-08 20:37:33 +02:00
parent eb64f2c411
commit a4d2b76bc5
43 changed files with 2772 additions and 1267 deletions
+2
View File
@@ -12,3 +12,5 @@ COUCHDB_URL="http://couchdb.unespace.com"
COUCHDB_DATABASE="headupdb"
COUCHDB_DESIGN="headup_app"
COUCHDB_CREDENTIAL="cmFtcGV1cjpES3hwMjRQUw=="
SKYDIVERID_API_URL="https://skydiver.id/api"
SKYDIVERID_API_TOKEN="xmqzgnGYMD.OJgFw1pCXCpJFGmZfSjmWK8lrpqAQNnu"
+2
View File
@@ -12,3 +12,5 @@ COUCHDB_URL="http://couchdb.unespace.com"
COUCHDB_DATABASE="headupdb"
COUCHDB_DESIGN="headup_app"
COUCHDB_CREDENTIAL="cmFtcGV1cjpES3hwMjRQUw=="
SKYDIVERID_API_URL="https://skydiver.id/api"
SKYDIVERID_API_TOKEN="xmqzgnGYMD.OJgFw1pCXCpJFGmZfSjmWK8lrpqAQNnu"
+2
View File
@@ -12,3 +12,5 @@ COUCHDB_URL="http://couchdb.unespace.com"
COUCHDB_DATABASE="headupdb"
COUCHDB_DESIGN="headup_app"
COUCHDB_CREDENTIAL="cmFtcGV1cjpES3hwMjRQUw=="
SKYDIVERID_API_URL="https://skydiver.id/api"
SKYDIVERID_API_TOKEN="xmqzgnGYMD.OJgFw1pCXCpJFGmZfSjmWK8lrpqAQNnu"
+28 -1
View File
@@ -34,6 +34,33 @@ node_modules
# Optional REPL history
.node_repl_history
.idea
# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# System files
.DS_Store
Thumbs.db
# SonarQube
.scannerwork/
sonar.properties
**/*.copy.ts
**/*.copy.scss
**/*.copy.html
middlewares
+28 -33
View File
@@ -6,7 +6,8 @@ require('dotenv').config({ path: `.env.${appEnv}` });
const { promisify } = require('util'),
bodyParser = require('body-parser'),
chalk = require('chalk'),
utils = require('./routes/utils');
utils = require('./routes/utils'),
exceptionHandler = require('./middlewares/exceptions.handler.js');
var express = require('express'),
session = require('express-session'),
cors = require('cors'),
@@ -23,8 +24,8 @@ app.use(cors());
// Normal express config defaults
//app.use(morgan('combined'));
morgan.token('statusColor', (req, res, args) => {
var status = (typeof res.headersSent !== 'boolean' ? Boolean(res.header) : res.headersSent)
morgan.token('statusColor', (req, res) => {
let status = (typeof res.headersSent !== 'boolean' ? Boolean(res.header) : res.headersSent)
? res.statusCode
: undefined
@@ -60,55 +61,49 @@ if(isProduction){
mongoose.set('debug', process.env.DEBUG);
console.log(`${utils.getDateTimeISOString()}`, chalk.red('debug :'), chalk.yellow(process.env.DEBUG));
}
require('./models/mongo/User');
require('./models/mongo/Application');
require('./models/mongo/Aeronef');
require('./models/mongo/Canopy');
require('./models/mongo/Dropzone');
require('./models/mongo/Jump');
require('./models/mongo/QCM');
/*
require('./models/mongo/Metal');
require('./models/mongo/Price');
require('./models/mongo/Product');
*/
require('./models/mongo');
require('./config/passport');
app.use(require('./routes'));
/// catch 404 and forward to error handler
app.use(exceptionHandler.notFoundErrorHandler);
app.use(exceptionHandler.logErrorHandler);
app.use(exceptionHandler.clientErrorHandler);
app.use(exceptionHandler.fianlErrorHandler);
/*
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
let err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (!isProduction) {
app.use(function(err, req, res, next) {
console.log(`${utils.getDateTimeISOString()}`, chalk.red(`error handler : ${err.message} ${err.err}`));
res.status(err.status || 500);
// error handler
app.use(function(err, req, res, next) {
console.log(`${utils.getDateTimeISOString()}`, chalk.red(`error handler : ${err.message} ${err.err}`));
if (res.headersSent) {
return next(err)
}
res.status(err.status || 500);
if (!isProduction) {
// development error handler will print stacktrace
res.json({errors: {
message: err.message,
error: err.err,
stack: err.stack
}});
});
} else {
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
} else {
// production error handler no stacktraces leaked to user
res.json({errors: {
message: err.message,
error: {},
stack: {}
}});
});
}
}
});
*/
const startServer = async () => {
const port = process.env.SERVER_PORT || 3200;
+9
View File
@@ -0,0 +1,9 @@
import globals from "globals";
import pluginJs from "@eslint/js";
export default [
{files: ["**/*.js"], languageOptions: {sourceType: "commonjs"}},
{languageOptions: { globals: globals.node }},
pluginJs.configs.recommended,
];
+12
View File
@@ -0,0 +1,12 @@
exports.User = require('./mongo/User');
exports.Application = require('./mongo/Application');
exports.Aeronef = require('./mongo/Aeronef');
exports.Canopy = require('./mongo/Canopy');
exports.Dropzone = require('./mongo/Dropzone');
exports.JumpFile = require('./mongo/JumpFile');
exports.Jump = require('./mongo/Jump');
exports.Qcm = require('./mongo/Qcm');
exports.QcmCategory = require('./mongo/QcmCategory');
exports.QcmQuestion = require('./mongo/QcmQuestion');
exports.QcmChoice = require('./mongo/QcmChoice');
exports.X2DataLog = require('./mongo/X2DataLog');
-1
View File
@@ -1,5 +1,4 @@
var mongoose = require('mongoose');
var User = mongoose.model('User');
var slug = require('slug');
var AeronefSchema = new mongoose.Schema({
-1
View File
@@ -1,5 +1,4 @@
var mongoose = require('mongoose');
var User = mongoose.model('User');
var slug = require('slug');
var CanopySchema = new mongoose.Schema({
-20
View File
@@ -1,20 +0,0 @@
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var CurrencySchema = new mongoose.Schema({
ordering: Number,
code: { type: String, upercase: true, unique: true },
title: String
}, {timestamps: true, toJSON: {virtuals: true}});
CurrencySchema.plugin(uniqueValidator, { message: 'is already taken' });
CurrencySchema.methods.toJSONFor = function(){
return {
ordering: this.ordering,
code: this.code,
title: this.title
};
};
mongoose.model('Currency', CurrencySchema, 'currencies');
-1
View File
@@ -1,5 +1,4 @@
var mongoose = require('mongoose');
var User = mongoose.model('User');
var slug = require('slug');
var DropzoneSchema = new mongoose.Schema({
+17 -2
View File
@@ -1,5 +1,4 @@
var mongoose = require('mongoose');
var User = mongoose.model('User');
var uniqueValidator = require('mongoose-unique-validator');
var slug = require('slug');
@@ -24,6 +23,8 @@ var JumpSchema = new mongoose.Schema({
zone: String,
dossier: String,
video: String,
files: [{ type: mongoose.Schema.Types.ObjectId, ref: 'JumpFile' }],
x2data: { type: mongoose.Schema.Types.ObjectId, ref: 'X2DataLog' },
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}, {timestamps: true, toJSON: {virtuals: true}});
@@ -40,7 +41,19 @@ JumpSchema.methods.slugify = function () {
this.slug = slug(`${this.numero} ${this.lieu}`) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36);
};
JumpSchema.methods.toJSONFor = function(user){
JumpSchema.methods.addFile = function (id) {
if (this.files.indexOf(id) === -1) {
this.files.push(id);
}
return this.save();
};
JumpSchema.methods.removeFile = function (id) {
this.files.remove(id);
return this.save();
};
JumpSchema.methods.toJSONFor = function(user) {
return {
slug: this.slug,
date: this.date,
@@ -62,6 +75,8 @@ JumpSchema.methods.toJSONFor = function(user){
zone: this.zone,
dossier: this.dossier,
video: this.video,
files: this.files.map(file => file ? file.toJSONForJump() : null),
x2data: this.x2data ? this.x2data.toJSONFor() : null,
createdAt: this.createdAt,
updatedAt: this.updatedAt,
author: this.author.toProfileJSONFor(user)
+51
View File
@@ -0,0 +1,51 @@
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var slug = require('slug');
var JumpFileSchema = new mongoose.Schema({
slug: { type: String, lowercase: true, unique: true },
name: String,
path: String,
type: {
type: String,
enum : ['csv', 'image', 'kml', 'video'],
default: 'video'
},
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}, {timestamps: true, toJSON: {virtuals: true}});
JumpFileSchema.plugin(uniqueValidator, { message: 'is already taken' });
JumpFileSchema.pre('validate', function (next) {
if (!this.slug) {
this.slugify();
}
next();
});
JumpFileSchema.methods.slugify = function () {
this.slug = slug(`${this.type}`) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36) + (Math.random() * Math.pow(36, 6) | 0).toString(36);
};
JumpFileSchema.methods.toJSONFor = function(user){
return {
slug: this.slug,
name: this.name,
path: this.path,
type: this.type,
createdAt: this.createdAt,
updatedAt: this.updatedAt,
author: this.author.toProfileJSONFor(user)
};
};
JumpFileSchema.methods.toJSONForJump = function(){
return {
slug: this.slug,
name: this.name,
path: this.path,
type: this.type
};
};
mongoose.model('JumpFile', JumpFileSchema);
-24
View File
@@ -1,24 +0,0 @@
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var MetalSchema = new mongoose.Schema({
ordering: Number,
code: { type: String, upercase: true, unique: true },
title: String,
color: String,
image: String
}, {timestamps: true, toJSON: {virtuals: true}});
MetalSchema.plugin(uniqueValidator, { message: 'is already taken' });
MetalSchema.methods.toJSONFor = function(){
return {
ordering: this.ordering,
code: this.code,
title: this.title,
color: this.color,
image: this.image
};
};
mongoose.model('Metal', MetalSchema);
-87
View File
@@ -1,87 +0,0 @@
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var PriceSchema = new mongoose.Schema({
timestamp: { type: Number, default: 0 },
metal: { type: String, upercase: true, default: 'ØØØ' },
currency: { type: String, upercase: true, default: 'ØØØ' },
exchange: { type: String, upercase: true, default: '' },
symbol: { type: String, upercase: true, default: '' },
prev_close_price: { type: Number, default: 0 },
open_price: { type: Number, default: 0 },
low_price: { type: Number, default: 0 },
high_price: { type: Number, default: 0 },
open_time: { type: Number, default: 0 },
price: { type: Number, default: 0 },
ch: { type: Number, default: 0 },
chp: { type: Number, default: 0 },
ask: { type: Number, default: 0 },
bid: { type: Number, default: 0 },
price_gram_24k: { type: Number, default: 0 },
price_gram_22k: { type: Number, default: 0 },
price_gram_21k: { type: Number, default: 0 },
price_gram_20k: { type: Number, default: 0 },
price_gram_18k: { type: Number, default: 0 },
price_gram_16k: { type: Number, default: 0 },
price_gram_14k: { type: Number, default: 0 },
price_gram_10k: { type: Number, default: 0 }
}, { timestamps: true, toJSON: { virtuals: true } });
PriceSchema.plugin(uniqueValidator, { message: 'is already taken' });
PriceSchema.methods.toJSONFor = function () {
/*
let a = {
timestamp: 1689944788,
metal: "XAU",
currency: "EUR",
exchange: "FOREXCOM",
symbol: "FOREXCOM:XAUEUR",
prev_close_price: 0.00,
open_price: 0.00,
low_price: 0.00,
high_price: 0.00,
open_time: 1689897600,
price: 0.00,
ch: 0.00,
chp: 0.00,
ask: 0.00,
bid: 0.00,
price_gram_24k: 0.00,
price_gram_22k: 0.00,
price_gram_21k: 0.00,
price_gram_20k: 0.00,
price_gram_18k: 0.00,
price_gram_16k: 0.00,
price_gram_14k: 0.00,
price_gram_10k: 0.00
};
*/
return {
timestamp: this.timestamp,
metal: this.metal,
currency: this.currency,
exchange: this.exchange,
symbol: this.symbol,
prev_close_price: this.prev_close_price,
open_price: this.open_price,
low_price: this.low_price,
high_price: this.high_price,
open_time: this.open_time,
price: this.price,
ch: this.ch,
chp: this.chp,
ask: this.ask,
bid: this.bid,
price_gram_24k: this.price_gram_24k,
price_gram_22k: this.price_gram_22k,
price_gram_21k: this.price_gram_21k,
price_gram_20k: this.price_gram_20k,
price_gram_18k: this.price_gram_18k,
price_gram_16k: this.price_gram_16k,
price_gram_14k: this.price_gram_14k,
price_gram_10k: this.price_gram_10k
};
};
mongoose.model('Price', PriceSchema);
-58
View File
@@ -1,58 +0,0 @@
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var slug = require('slug');
var User = mongoose.model('User');
var ProductSchema = new mongoose.Schema({
ordering: Number,
title: String,
slug: { type: String, lowercase: true, unique: true },
prime_achat: Number,
prime_vente: Number,
metal: { type: mongoose.Schema.Types.ObjectId, ref: 'Metal' },
poids: Number,
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
favoritesCount: { type: Number, default: 0 }
}, {timestamps: true, toJSON: {virtuals: true}});
ProductSchema.plugin(uniqueValidator, { message: 'is already taken' });
ProductSchema.pre('validate', function (next) {
if (!this.slug) {
this.slugify();
}
next();
});
ProductSchema.methods.slugify = function () {
this.slug = slug(this.title) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36);
};
ProductSchema.methods.updateFavoriteCount = function () {
var product = this;
return User.count({ favorites: { $in: [product._id] } }).then(function (count) {
product.favoritesCount = count;
return product.save();
});
};
ProductSchema.methods.toJSONFor = function(user){
return {
ordering: this.ordering,
title: this.title,
slug: this.slug,
prime_achat: this.prime_achat,
prime_vente: this.prime_vente,
metal: this.metal.toJSONFor(),
poids: this.poids,
createdAt: this.createdAt,
updatedAt: this.updatedAt,
favorited: user ? user.isFavorite(this._id) : false,
favoritesCount: this.favoritesCount,
author: this.author.toProfileJSONFor(user)
};
};
mongoose.model('Product', ProductSchema);
+31 -8
View File
@@ -2,22 +2,45 @@ var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var slug = require('slug');
var QCMSchema = new mongoose.Schema({
var QcmSchema = new mongoose.Schema({
name: { type: String, lowercase: true, unique: true },
slug: { type: String, lowercase: true, unique: true },
categories: [
{ type: mongoose.Schema.Types.ObjectId, ref: 'QCMCategory' }
{ type: mongoose.Schema.Types.ObjectId, ref: 'QcmCategory' }
]
}, {timestamps: true, toJSON: {virtuals: true}});
QCMSchema.plugin(uniqueValidator, { message: 'is already taken' });
QcmSchema.plugin(uniqueValidator, { message: 'is already taken' });
QCMSchema.methods.toJSONFor = function(){
QcmSchema.pre('validate', function (next) {
if (!this.slug) {
this.slugify();
}
next();
});
QcmSchema.methods.slugify = function () {
this.slug = slug(`${this.name}-`) + (Math.random() * Math.pow(36, 6) | 0).toString(36);
};
QcmSchema.methods.addCategory = function (id) {
if (this.categories.indexOf(id) === -1) {
this.categories.push(id);
}
return this.save();
};
QcmSchema.methods.removeCategory = function (id) {
this.categories.remove(id);
return this.save();
};
QcmSchema.methods.toJSONFor = function() {
return {
name: this.name,
categories: this.categories,
createdAt: this.createdAt,
updatedAt: this.updatedAt
slug: this.slug,
categories: this.categories.map(category => category.toJSONFor())
};
};
mongoose.model('QCM', QCMSchema);
mongoose.model('Qcm', QcmSchema);
-23
View File
@@ -1,23 +0,0 @@
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var slug = require('slug');
var QCMCategorySchema = new mongoose.Schema({
num: number,
name: { type: String, lowercase: true, unique: true },
questions: []
}, {timestamps: true, toJSON: {virtuals: true}});
QCMCategorySchema.plugin(uniqueValidator, { message: 'is already taken' });
QCMCategorySchema.methods.toJSONFor = function(){
return {
num: this.num,
name: this.name,
questions: this.questions,
createdAt: this.createdAt,
updatedAt: this.updatedAt
};
};
mongoose.model('QCMCategory', QCMCategorySchema);
+48
View File
@@ -0,0 +1,48 @@
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var slug = require('slug');
var QcmCategorySchema = new mongoose.Schema({
num: Number,
name: { type: String, unique: true },
slug: { type: String, lowercase: true, unique: true },
questions: [
{ type: mongoose.Schema.Types.ObjectId, ref: 'QcmQuestion' }
]
}, {timestamps: true, toJSON: {virtuals: true}});
QcmCategorySchema.plugin(uniqueValidator, { message: 'is already taken' });
QcmCategorySchema.pre('validate', function (next) {
if (!this.slug) {
this.slugify();
}
next();
});
QcmCategorySchema.methods.slugify = function () {
this.slug = slug(`${this.name}-${this.num}-`) + (Math.random() * Math.pow(36, 6) | 0).toString(36);
};
QcmCategorySchema.methods.addQuestion = function (id) {
if (this.questions.indexOf(id) === -1) {
this.questions.push(id);
}
return this.save();
};
QcmCategorySchema.methods.removeQuestion = function (id) {
this.questions.remove(id);
return this.save();
};
QcmCategorySchema.methods.toJSONFor = function() {
return {
num: this.num,
name: this.name,
slug: this.slug,
questions: this.questions.map(question => question.toJSONFor())
};
};
mongoose.model('QcmCategory', QcmCategorySchema);
+17
View File
@@ -0,0 +1,17 @@
var mongoose = require('mongoose');
var QcmChoiceSchema = new mongoose.Schema({
index: String,
libelle: String,
correct: Boolean
}, {timestamps: true, toJSON: {virtuals: true}});
QcmChoiceSchema.methods.toJSONFor = function() {
return {
index: this.index,
libelle: this.libelle,
correct: this.correct
};
};
mongoose.model('QcmChoice', QcmChoiceSchema);
+31
View File
@@ -0,0 +1,31 @@
var mongoose = require('mongoose');
var QcmQuestionSchema = new mongoose.Schema({
num: Number,
libelle: String,
choices: [
{ type: mongoose.Schema.Types.ObjectId, ref: 'QcmChoice' }
]
}, {timestamps: true, toJSON: {virtuals: true}});
QcmQuestionSchema.methods.addChoice = function (id) {
if (this.choices.indexOf(id) === -1) {
this.choices.push(id);
}
return this.save();
};
QcmQuestionSchema.methods.removeChoice = function (id) {
this.choices.remove(id);
return this.save();
};
QcmQuestionSchema.methods.toJSONFor = function() {
return {
num: this.num,
libelle: this.libelle,
choices: this.choices.map(choice => choice.toJSONFor())
};
};
mongoose.model('QcmQuestion', QcmQuestionSchema);
+3 -3
View File
@@ -24,7 +24,7 @@ var UserSchema = new mongoose.Schema({
UserSchema.plugin(uniqueValidator, { message: 'is already taken.' });
UserSchema.methods.validPassword = function (password) {
var hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512').toString('hex');
let hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512').toString('hex');
return this.hash === hash;
};
@@ -34,8 +34,8 @@ UserSchema.methods.setPassword = function (password) {
};
UserSchema.methods.generateJWT = function () {
var today = new Date();
var exp = new Date(today);
let today = new Date();
let exp = new Date(today);
exp.setDate(today.getDate() + 60);
return jwt.sign({
+107
View File
@@ -0,0 +1,107 @@
var mongoose = require('mongoose');
var X2DataLogSchema = new mongoose.Schema({
id: String,
name: String,
type: String,
description: String,
landingZone: String,
speed: {
freeFall: {
vertical: {
max: Number,
avg: Number
},
horizontal: {
max: Number,
avg: Number
}
},
underCanopy: {
vertical: {
max: Number,
avg: Number
},
horizontal: {
max: Number,
avg: Number
}
}
},
glideRatio: {
freeFall: {
max: Number,
avg: Number
},
underCanopy: {
max: Number,
avg: Number
}
},
duration: {
freeFall: Number,
underCanopy: Number
},
distance: {
exitFromLandingZone: Number,
totalFlying: Number,
totalHorizontal: Number
},
altitude: {
exit: Number,
deployment: Number
},
cutaway: String,
malfunctions: [
{
name: String,
type: String
}
],
date: String,
createdOn: String,
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}, {timestamps: true, toJSON: {virtuals: true}});
X2DataLogSchema.methods.toJSONFor = function() {
return {
id: this.id,
name: this.name,
type: this.type,
description: this.description,
landingZone: this.landingZone,
speed: this.speed,
glideRatio: this.glideRatio,
duration: this.duration,
distance: this.distance,
altitude: this.altitude,
cutaway: this.cutaway,
malfunctions: this.malfunctions,
date: this.date,
createdOn: this.createdOn
};
};
X2DataLogSchema.methods.toJSONForUser = function(user) {
return {
id: this.id,
name: this.name,
type: this.type,
description: this.description,
landingZone: this.landingZone,
speed: this.speed,
glideRatio: this.glideRatio,
duration: this.duration,
distance: this.distance,
altitude: this.altitude,
cutaway: this.cutaway,
malfunctions: this.malfunctions,
date: this.date,
createdOn: this.createdOn,
createdAt: this.createdAt,
updatedAt: this.updatedAt,
author: this.author.toProfileJSONFor(user)
};
};
mongoose.model('X2DataLog', X2DataLogSchema);
+13
View File
@@ -0,0 +1,13 @@
exports.User = require('./User');
exports.Application = require('./Application');
exports.Aeronef = require('./Aeronef');
exports.Canopy = require('./Canopy');
exports.Dropzone = require('./Dropzone');
exports.JumpFile = require('./JumpFile');
exports.Jump = require('./Jump');
exports.Qcm = require('./Qcm');
exports.QcmCategory = require('./QcmCategory');
exports.QcmQuestion = require('./QcmQuestion');
exports.QcmChoice = require('./QcmChoice');
exports.X2DataLog = require('./X2DataLog');
+3 -1
View File
@@ -13,6 +13,8 @@
"COUCHDB_URL": "http://couchdb.unespace.com",
"COUCHDB_DATABASE": "headupdb",
"COUCHDB_DESIGN": "headup_app",
"COUCHDB_CREDENTIAL": "cmFtcGV1cjpES3hwMjRQUw=="
"COUCHDB_CREDENTIAL": "cmFtcGV1cjpES3hwMjRQUw==",
"SKYDIVERID_API_URL": "https://skydiver.id/api",
"SKYDIVERID_API_TOKEN": "xmqzgnGYMD.OJgFw1pCXCpJFGmZfSjmWK8lrpqAQNnu"
}
}
+858 -1
View File
File diff suppressed because it is too large Load Diff
+3
View File
@@ -48,6 +48,9 @@
"uuid": "^9.0.1"
},
"devDependencies": {
"@eslint/js": "^9.0.0",
"eslint": "^9.0.0",
"globals": "^15.0.0",
"newman": "^5.3.2",
"nodemon": "^2.0.22"
}
+83 -74
View File
@@ -1,14 +1,14 @@
var router = require('express').Router(),
mongoose = require('mongoose'),
Aeronef = mongoose.model('Aeronef'),
Jump = mongoose.model('Jump'),
User = mongoose.model('User');
const auth = require('../auth');
const auth = require('../auth'),
queries = require('../queries');
router.get('/', auth.required, function (req, res, next) {
var limit = 25;
var offset = 0;
router.get('/allByImat', auth.required, function (req, res, next) {
let limit = 25;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
@@ -18,43 +18,22 @@ router.get('/', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
var query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': user._id.toString() } ]
}
}
}, {
'$group': {
'_id': {
'aeronef': '$aeronef',
'imat': '$imat'
},
'count': {
'$sum': 1
}
}
}, {
'$sort':
{
'_id': 1
},
}
];
let query = queries.getAeronefsByImatQuery(user._id.toString());
Promise.all([
Jump.aggregate(query)
.limit(Number(limit))
.skip(Number(offset))
.limit(Number(limit))
.exec()
//Aeronef.count(query)
]).then(function (results) {
var aeronefs = results[0];
//var aeronefsCount = results[1];
let aeronefs = results[0];
//let aeronefsCount = results[1];
return res.json({
aeronefs: aeronefs,
aeronefs: aeronefs.map(function (data) {
return { aeronef: data._id.aeronef, imat: data._id.imat, count: data.count };
}),
aeronefsCount: aeronefs.length
});
/*
@@ -69,66 +48,96 @@ router.get('/', auth.required, function (req, res, next) {
}).catch(next);
});
router.get('/allByDate', auth.required, function (req, res, next) {
router.get('/allByImatByYear', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
var limit = 50;
var offset = 0;
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;
}
var query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': user._id.toString() } ]
}
}
}, {
'$project': {
'_id': 0,
'aeronef': 1,
'imat': 1,
'year': {
'$year': '$date'
}
}
}, {
'$group': {
'_id': {
'aeronef': '$aeronef',
'imat': '$imat',
'year': '$year'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
let query = queries.getAeronefsByImatByYearQuery(user._id.toString());
Jump.aggregate(query)
.limit(Number(limit))
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
var aeronefs = result;
//console.log(aeronefs);
let aeronefs = result.map(function (data) {
return { aeronef: data._id.aeronef, imat: data._id.imat, year: data._id.year, count: data.count };
});
return res.json({
aeronefs: aeronefs,
aeronefsCount: aeronefs.length
});
}).catch(next);
}).catch(next);
/*
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;
}
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': user._id.toString() } ]
}
}
}, {
'$project': {
'_id': 0,
'aeronef': 1,
'imat': 1,
'year': {
'$year': '$date'
}
}
}, {
'$group': {
'_id': {
'aeronef': '$aeronef',
'imat': '$imat',
'year': '$year'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
Promise.all([
req.payload ? User.findById(req.payload.id) : null,
Jump.aggregate(query)
.skip(Number(offset))
.limit(Number(limit))
.exec()
]).then(function (results) {
let user = results[0];
let aeronefs = results[1];
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
return res.json({
aeronefs: aeronefs,
aeronefsCount: aeronefs.length
});
}).catch(next);
*/
});
module.exports = router;
+16 -16
View File
@@ -21,9 +21,9 @@ router.param('application', function (req, res, next, slug) {
});
router.get('/', auth.required, function (req, res, next) {
var query = {};
var limit = 25;
var offset = 0;
let query = {};
let limit = 25;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
@@ -46,17 +46,17 @@ router.get('/', auth.required, function (req, res, next) {
}
return Promise.all([
Application.find(query)
.limit(Number(limit))
.skip(Number(offset))
.limit(Number(limit))
.sort({ createdAt: 'desc' })
.populate('author')
.exec(),
Application.count(query).exec(),
req.payload ? User.findById(req.payload.id) : null
]).then(function (results) {
var applications = results[0];
var applicationsCount = results[1];
var user = results[2];
let applications = results[0];
let applicationsCount = results[1];
let user = results[2];
return res.json({
applications: applications.map(function (application) {
@@ -73,17 +73,17 @@ router.post('/', auth.required, function (req, res, next) {
User.findById(req.payload.id),
auth.generateAPIKey()
]).then(function (results) {
var user = results[0];
var keys = results[1];
let user = results[0];
let keys = results[1];
if (!user) {
return res.sendStatus(401).json({message: "Unauthorized - You are not allowed to access this resource."});
}
var application = new Application(req.body.application);
let application = new Application(req.body.application);
application.author = user;
application.apikey = keys.encrypted;
application.maskedkey = keys.masked;
return application.save().then(function () {
var msg = {
let msg = {
to: user.email,
from: process.env.SENDGRID_FROM_MAIL,
subject: `Api-Key ${application.title}`,
@@ -96,7 +96,7 @@ router.post('/', auth.required, function (req, res, next) {
<hr />
<p>${application.description}</p>`
};
mailer.send(msg).then(resp => {
mailer.send(msg).then(() => {
return res.json({ application: application.toJSONFor(user) });
})
.catch(err => {
@@ -112,7 +112,7 @@ router.get('/:application', auth.required, function (req, res, next) {
req.payload ? User.findById(req.payload.id) : null,
req.application.populate('author')
]).then(function (results) {
var user = results[0];
let user = results[0];
return res.json({ application: req.application.toJSONFor(user) });
}).catch(next);
});
@@ -136,7 +136,7 @@ router.put('/:application', auth.required, function (req, res, next) {
return res.json({ application: application.toJSONFor(user) });
}).catch(next);
} else {
return res.sendStatus(403);
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
});
});
@@ -145,14 +145,14 @@ router.put('/:application', auth.required, function (req, res, next) {
router.delete('/:application', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401).json({message: "Unauthorized - You are not allowed to access this resource."});
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
if (user.role == 'Admin' || req.application.author._id.toString() === req.payload.id.toString()) {
return req.application.remove().then(function () {
return res.sendStatus(204);
});
} else {
return res.sendStatus(403).json({message: "Forbidden - You are not allowed to access this resource."});
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
}).catch(next);
});
-129
View File
@@ -1,129 +0,0 @@
var router = require('express').Router();
const auth = require('../auth');
//var ExceptionsHandler = require('../../middlewares/exceptions.handler');
//var UnknownRoutesHandler = require('../../middlewares/unknownRoutes.handler');
router.use('/', function (req, res, next) {
let taxationValues = ['cours_legaux', 'jetons', 'metaux_precieux'];
let errors = [];
if (req.body.taxationType == undefined || taxationValues.indexOf(req.body.taxationType) === -1) {
errors.push('La valeur du paramètre \'taxationType\' est incorrecte.');
}
if (req.body.purchasePrice == undefined || req.body.purchasePrice <= 0) {
errors.push('La valeur du paramètre \'purchasePrice\' est incorrecte.');
}
if (req.body.sellPrice == undefined || req.body.sellPrice <= 0) {
errors.push('La valeur du paramètre \'sellPrice\' est incorrecte.');
}
if (req.body.yearOwnership == undefined || req.body.yearOwnership < 0) {
errors.push('La valeur du paramètre \'yearOwnership\' est incorrecte.');
}
if (errors.length) {
return res.status(422).json({
errors: {
name: 'ValidationError',
message: 'La validation des données a échoué.',
messages: errors
}
});
}
return next();
});
router.post('/', function (req, res, next) {
const config = {
palierDetention: 2,
coeff: {
metaux_precieux: 0.115,
jetons: 0.065,
plus_value: 0.362
}
};
const params = {
taxationType: req.body.taxationType ? req.body.taxationType : null,
purchasePrice: req.body.purchasePrice ? req.body.purchasePrice : 0,
sellPrice: req.body.sellPrice ? req.body.sellPrice : 0,
yearOwnership: req.body.yearOwnership ? req.body.yearOwnership : 0
};
let results = {
capitalGain: 0,
capitalGainCoeff: 0,
lumpSum: 0,
lumpSumCoeff: 0,
isTaxable: false,
bestChoice: null, // valeurs possibles : 'lumpSum', 'gain' or null
messages: []
}
if(req.body.purchasePrice >= req.body.sellPrice) {
results.messages.push((req.body.purchasePrice > req.body.sellPrice) ? 'Vous êtes dans le cas d\'une moins-value.' : 'Vous êtes dans le cas d\'une plus-value nulle.');
}
if(req.body.yearOwnership >= 22) {
results.messages.push('Vous êtes dans le cas d\'une vente non imposable (à partir de 22 ans de détention).');
}
if (params.sellPrice <= 5000) {
if (params.taxationType == 'cours_legaux') {
results.messages.push('Vous êtes dans le cas d\'une vente non imposable sur le cours légal (inférieure à 5000 €).');
} else if (params.taxationType == 'jetons') {
results.messages.push('Vous êtes dans le cas d\'une vente non imposable sur les jetons (inférieure à 5000 €).');
}
}
if (results.messages.length) {
results.messages.push('La déclaration est inutile, il n\'y a pas d\'imposition.');
return res.json({
params: params,
results: results
});
}
results.isTaxable = true;
results.capitalGainCoeff = config.coeff.plus_value;
if (params.yearOwnership > config.palierDetention) {
/* A partir de la deuxième année, abattement de 5% sur le taux appliqué */
results.capitalGainCoeff = roundNumber((config.coeff.plus_value - (config.coeff.plus_value * (0.05 * (params.yearOwnership - config.palierDetention)))), 4);
results.capitalGain = Math.floor(results.capitalGainCoeff * (params.sellPrice - params.purchasePrice));
} else {
results.capitalGain = Math.floor(config.coeff.plus_value * (params.sellPrice - params.purchasePrice));
}
let value = roundNumber((results.capitalGainCoeff * 100), 2);
results.messages.push(`Le montant du régime des plus-value (${value}%) est de ${results.capitalGain} €.`);
results.bestChoice = 'gain';
if (params.taxationType != 'cours_legaux') {
results.lumpSum = Math.floor(params.sellPrice * config.coeff[params.taxationType]);
if (results.lumpSum < results.capitalGain) {
results.bestChoice = 'lumpSum';
}
results.lumpSumCoeff = config.coeff[params.taxationType];
value = (config.coeff[params.taxationType] * 100 );
results.messages.push(`Le montant de la taxe forfaitaire (${value}%) est de ${results.lumpSum} €.`);
results.messages.push(`La meilleure option pour vous est ${(results.bestChoice == 'lumpSum') ? 'la taxe forfaitaire' : 'la taxe sur le régime des plus values'}.`);
if (params.taxationType == 'jetons') {
results.messages.push(`À noter : pour une revente de produits de jetons en dessous du seuil des 5000€, aucune taxe n'est applicable.`);
}
} else {
results.messages.push('La taxe forfaitaire n\'est pas applicable pour les produits à cours légaux. Seule la taxe sur le régime des plus-values est applicable.');
results.messages.push('À noter : pour une revente de produits à cours légaux en dessous du seuil des 5000 €, aucune taxe n\'est applicable.');
}
return res.json({
params: params,
results: results
});
});
router.all('*', function (req, res, next) {
return res.status(404).json({
errors: {
name: 'UnknownRouteError',
message: 'La route API demandée est introuvable.'
}
});
});
function roundNumber(num, dec){
var num_sign = num >= 0 ? 1 : -1;
return parseFloat((Math.round((num * Math.pow(10, dec)) + (num_sign * 0.0001)) / Math.pow(10, dec)).toFixed(dec));
}
module.exports = router;
+52 -156
View File
@@ -1,14 +1,14 @@
var router = require('express').Router(),
mongoose = require('mongoose'),
Canopy = mongoose.model('Canopy'),
Jump = mongoose.model('Jump'),
User = mongoose.model('User');
const auth = require('../auth');
const auth = require('../auth'),
queries = require('../queries');
router.get('/', auth.required, function (req, res, next) {
var query = {};
var limit = 25;
var offset = 0;
let query = {};
let limit = 25;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
@@ -21,17 +21,17 @@ router.get('/', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
if (user.role == 'Admin') {
return res.sendStatus(403);
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
Jump.find(query)
.limit(Number(limit))
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
var canopies = result;
let canopies = result;
return res.json({
canopies: canopies,
canopiesCount: canopies.length
@@ -41,8 +41,8 @@ router.get('/', auth.required, function (req, res, next) {
});
router.get('/allBySize', auth.required, function (req, res, next) {
var limit = 25;
var offset = 0;
let limit = 25;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
@@ -52,38 +52,17 @@ router.get('/allBySize', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
var query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': user._id.toString() } ]
}
}
}, {
'$group': {
'_id': {
'taille': '$taille'
},
'count': {
'$sum': 1
}
}
}, {
'$sort':
{
'_id': 1
},
}
];
Promise.all([
Jump.aggregate(query)
.limit(Number(limit))
.skip(Number(offset))
.exec()
]).then(function (results) {
var canopies = results[0];
let query = queries.getCanopiesBySizeQuery(user._id.toString());
Jump.aggregate(query)
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
let canopies = result.map(function (data) {
return { taille: data._id.taille, count: data.count };
});
return res.json({
canopies: canopies,
canopiesCount: canopies.length
@@ -92,57 +71,28 @@ router.get('/allBySize', auth.required, function (req, res, next) {
}).catch(next);
});
router.get('/allByYear', auth.required, function (req, res, next) {
router.get('/allBySizeByYear', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
var limit = 25;
var offset = 0;
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;
}
var query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': user._id.toString() } ]
}
}
}, {
'$project': {
'_id': 0,
'taille': 1,
'year': {
'$year': '$date'
}
}
}, {
'$group': {
'_id': {
'taille': '$taille',
'year': '$year'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
let query = queries.getCanopiesBySizeByYearQuery(user._id.toString());
Jump.aggregate(query)
.limit(Number(limit))
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
var canopies = result;
let canopies = result.map(function (data) {
return { taille: data._id.taille, year: data._id.year, count: data.count };
});
//console.log(dropzones);
return res.json({
canopies: canopies,
@@ -152,9 +102,9 @@ router.get('/allByYear', auth.required, function (req, res, next) {
}).catch(next);
});
router.get('/allModelBySize', auth.required, function (req, res, next) {
var limit = 25;
var offset = 0;
router.get('/allBySizeByModel', auth.required, function (req, res, next) {
let limit = 25;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
@@ -164,39 +114,17 @@ router.get('/allModelBySize', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
var query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': user._id.toString() } ]
}
}
}, {
'$group': {
'_id': {
'taille': '$taille',
'voile': '$voile'
},
'count': {
'$sum': 1
}
}
}, {
'$sort':
{
'_id': 1
},
}
];
Promise.all([
Jump.aggregate(query)
.limit(Number(limit))
.skip(Number(offset))
.exec()
]).then(function (results) {
var canopies = results[0];
let query = queries.getCanopiesBySizeByModelQuery(user._id.toString());
Jump.aggregate(query)
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
let canopies = result.map(function (data) {
return { taille: data._id.taille, voile: data._id.voile, count: data.count };
});
return res.json({
canopies: canopies,
canopiesCount: canopies.length
@@ -205,60 +133,28 @@ router.get('/allModelBySize', auth.required, function (req, res, next) {
}).catch(next);
});
router.get('/allModelByYear', auth.required, function (req, res, next) {
router.get('/allBySizeByModelByYear', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
var limit = 25;
var offset = 0;
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;
}
var query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': user._id.toString() } ]
}
}
}, {
'$project': {
'_id': 0,
'voile': 1,
'taille': 1,
'year': {
'$year': '$date'
}
}
}, {
'$group': {
'_id': {
'taille': '$taille',
'voile': '$voile',
'year': '$year'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
let query = queries.getCanopiesBySizeByModelByYearQuery(user._id.toString());
Jump.aggregate(query)
.limit(Number(limit))
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
var canopies = result;
//console.log(dropzones);
let canopies = result.map(function (data) {
return { taille: data._id.taille, voile: data._id.voile, year: data._id.year, count: data.count };
});
return res.json({
canopies: canopies,
canopiesCount: canopies.length
+20 -73
View File
@@ -1,54 +1,33 @@
var router = require('express').Router(),
mongoose = require('mongoose'),
Dropzone = mongoose.model('Dropzone'),
Jump = mongoose.model('Jump'),
User = mongoose.model('User');
const auth = require('../auth');
const auth = require('../auth'),
queries = require('../queries');
router.get('/', auth.required, function (req, res, next) {
router.get('/allByOaci', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
var limit = 25;
var offset = 0;
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;
}
var query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': user._id.toString() } ]
}
}
}, {
'$group': {
'_id': {
'lieu': '$lieu',
'oaci': '$oaci'
},
'count': {
'$sum': 1
}
}
}, {
'$sort':
{
'_id': 1
},
}
];
let query = queries.getDropZonesByOaciQuery(user._id.toString());
Jump.aggregate(query)
.limit(Number(limit))
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
var dropzones = result;
let dropzones = result.map(function (data) {
return { lieu: data._id.lieu, oaci: data._id.oaci, count: data.count };
});
return res.json({
dropzones: dropzones,
dropzonesCount: dropzones.length
@@ -57,60 +36,28 @@ router.get('/', auth.required, function (req, res, next) {
}).catch(next);
});
router.get('/allByDate', auth.required, function (req, res, next) {
router.get('/allByOaciByYear', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
var limit = 25;
var offset = 0;
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;
}
var query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': user._id.toString() } ]
}
}
}, {
'$project': {
'_id': 0,
'lieu': 1,
'oaci': 1,
'year': {
'$year': '$date'
}
}
}, {
'$group': {
'_id': {
'lieu': '$lieu',
'oaci': '$oaci',
'year': '$year'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
let query = queries.getDropZonesByOaciByYearQuery(user._id.toString());
Jump.aggregate(query)
.limit(Number(limit))
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
var dropzones = result;
//console.log(dropzones);
let dropzones = result.map(function (data) {
return { lieu: data._id.lieu, oaci: data._id.oaci, year: data._id.year, count: data.count };
});
return res.json({
dropzones: dropzones,
dropzonesCount: dropzones.length
+2 -6
View File
@@ -7,13 +7,9 @@ router.use('/aeronefs', require('./aeronefs'));
router.use('/canopies', require('./canopies'));
router.use('/dropzones', require('./dropzones'));
router.use('/jumps', require('./jumps'));
router.use('/pages', require('./pages'));
router.use('/qcm', require('./qcm'));
/*
router.use('/products', require('./products'));
router.use('/metals', require('./metals'));
router.use('/prices', require('./prices'));
router.use('/calcul', require('./calcul'));
*/
router.use(function (err, req, res, next) {
if (err.name === 'ValidationError') {
return res.status(422).json({
+363 -90
View File
@@ -1,13 +1,20 @@
var router = require('express').Router(),
mongoose = require('mongoose'),
Jump = mongoose.model('Jump'),
User = mongoose.model('User');
const auth = require('../auth');
JumpFile = mongoose.model('JumpFile'),
User = mongoose.model('User'),
X2DataLog = mongoose.model('X2DataLog');
const auth = require('../auth'),
chalk = require('chalk'),
queries = require('../queries'),
utils = require('../utils');
// 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);
@@ -21,9 +28,9 @@ router.param('jump', function (req, res, next, slug) {
* return all jumps
*/
router.get('/', auth.required, function (req, res, next) {
var query = {};
var limit = 25;
var offset = 0;
let query = {};
let limit = 25;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
@@ -39,31 +46,87 @@ router.get('/', auth.required, function (req, res, next) {
],
}
}
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 ? User.findOne({ username: req.query.author }) : null,
req.query.favorited ? User.findOne({ username: req.query.favorited }) : null
]).then(function (users) {
var author = users[0];
let author = users[0];
if (author) {
query.author = author._id;
}
return Promise.all([
Promise.all([
Jump.find(query)
.limit(Number(limit))
.skip(Number(offset))
.limit(Number(limit))
.sort({ numero: 'desc' })
.populate('author')
.populate('files')
.populate('x2data')
.exec(),
Jump.count(query).exec(),
req.payload ? User.findById(req.payload.id) : null
]).then(function (results) {
var jumps = results[0];
var jumpsCount = results[1];
var user = results[2];
let jumps = results[0];
let jumpsCount = results[1];
let user = results[2];
/*
Promise.all(
jumps.map(jump => {
if (jump.files[0] !== undefined && jump.files[0].type !== 'kml') {
console.log( chalk.green(`Fichier ${jump.files[0].type}`))
//console.log( chalk.green(`Suppression du fichier ${jump.files[2]._id}`))
//return jump.removeFile(jump.files[2]._id);
}
return;
})
).then(function () {
return res.json({
jumps: jumps.map(function (jump) {
return jump.toJSONFor(user);
}),
jumpsCount: jumpsCount
});
});
*/
return res.json({
jumps: jumps.map(function (jump) {
return jump.toJSONFor(user);
@@ -74,60 +137,29 @@ router.get('/', auth.required, function (req, res, next) {
}).catch(next);
});
router.get('/allByDate', auth.required, function (req, res, next) {
router.get('/allByCategorie', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
var limit = 120;
var offset = 0;
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;
}
var query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': user._id.toString() } ]
}
}
}, {
'$project': {
'_id': 0,
'year': {
'$year': '$date'
},
'month': {
'$month': '$date'
}
}
}, {
'$group': {
'_id': {
'year': '$year',
'month': '$month'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
let query = queries.getJumpsByCategoryQuery(user._id.toString());
Jump.aggregate(query)
.limit(Number(limit))
.skip(Number(offset))
.limit(Number(limit))
.exec()
.then(function (result) {
var jumps = result;
//console.log(jumps);
let jumps = result.map(function (data) {
return { categorie: data._id.categorie, count: data.count };
});
return res.json({
jumps: jumps,
jumpsCount: jumps.length
@@ -136,10 +168,133 @@ router.get('/allByDate', auth.required, function (req, res, next) {
}).catch(next);
});
router.get('/allByDate', auth.required, function (req, res, next) {
User.findById(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.toString());
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) {
User.findById(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.toString(),
req.query.dateRangeStart,
req.query.dateRangeEnd
);
} else {
query = queries.getJumpsByDayQuery(user._id.toString());
}
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) {
User.findById(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.toString());
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) {
User.findById(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(`${utils.getDateTimeISOString()}`, chalk.green(`Réception des sauts SkydiverId`));
} else {
console.log(`${utils.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);
});
router.get('/feed', auth.required, function (req, res, next) {
var limit = 25;
var offset = 0;
let limit = 25;
let offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
@@ -149,19 +304,21 @@ router.get('/feed', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
var query = { author: { $in: user.following } };
let query = { author: { $in: user.following } };
Promise.all([
Jump.find(query)
.limit(Number(limit))
.skip(Number(offset))
.limit(Number(limit))
.populate('author')
.populate('files')
.populate('x2data')
.exec(),
Jump.count(query)
]).then(function (results) {
var jumps = results[0];
var jumpsCount = results[1];
let jumps = results[0];
let jumpsCount = results[1];
return res.json({
jumps: jumps.map(function (jump) {
return jump.toJSONFor(user);
@@ -176,10 +333,9 @@ router.get('/feed', auth.required, function (req, res, next) {
* return last jump
*/
router.get('/last', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
/*Jump.findOne({ slug: slug })
.populate('author')
@@ -192,9 +348,10 @@ router.get('/last', auth.required, function (req, res, next) {
}).catch(next);*/
Jump.find({})
.limit(1)
.skip(0)
.sort({ numero: 'desc' })
.populate('author')
.populate('files')
.populate('x2data')
.exec()
.then(function (jumps) {
if (!jumps) {
@@ -202,28 +359,34 @@ router.get('/last', auth.required, function (req, res, next) {
}
req.lastjump = jumps[0];
if (req.lastjump.author._id.toString() !== req.payload.id.toString()) {
return res.sendStatus(403);
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
return res.json({ jump: req.lastjump.toJSONFor(user) });
}).catch(next);
}).catch(next);
});
/**
* return a jump
*/
router.get('/:jump', auth.required, function (req, res, next) {
Promise.all([
req.payload ? User.findById(req.payload.id) : null
/*req.jump.populate('author')*/
]).then(function (results) {
var user = results[0];
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
if (req.jump.author._id.toString() !== req.payload.id.toString()) {
return res.sendStatus(403);
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
return res.json({ jump: req.jump.toJSONFor(user) });
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(user),
prevJump: results[0],
nextJump: results[1]
});
}).catch(next);
}).catch(next);
});
@@ -231,19 +394,12 @@ router.get('/:jump', auth.required, function (req, res, next) {
* save a jump
*/
router.post('/', auth.required, function (req, res, next) {
Promise.all([
req.payload ? User.findById(req.payload.id) : null
/*Jump
.find({}).select('numero')
.sort({"numero" : -1}).limit(1)
.exec()*/
]).then(function (results) {
var user = results[0];
//var numero = (results[1][0].numero + 1);
User.findById(req.payload.id).then(function (user) {
//let numero = (results[1][0].numero + 1);
if (!user) {
return res.sendStatus(401);
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
var jump = new Jump(req.body.jump);
let jump = new Jump(req.body.jump);
jump.author = user;
//jump.numero = numero;
return jump.save().then(function () {
@@ -252,19 +408,136 @@ router.post('/', auth.required, function (req, res, next) {
}).catch(next);
});
/**
* save a jump file
*/
router.post('/data/:jump', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
if (req.jump.author._id.toString() !== req.payload.id.toString()) {
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
/*
console.log(req.jump.files);
return res.json({ jump: req.jump.toJSONFor(user) });
*/
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;
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;
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(user) });
}).catch(next);
}).catch(next);
}).catch(next);
}).catch(next);
});
/**
* save a jump file
*/
router.post('/file/:jump', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
if (req.jump.author._id.toString() !== req.payload.id.toString()) {
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;
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 file
*/
router.post('/kml/:jump', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
if (req.jump.author._id.toString() !== req.payload.id.toString()) {
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;
files.push(file);
//console.log(chalk.yellow(`jump/${req.jump.x2data.id}/kml`));
return res.json({ file: file.toJSONForJump() });
/*
utils.fetchSkydiverIdApi(`jump/${req.jump.x2data.id}/kml`, {}).then(result => {
if (result.errors === undefined) {
console.log(`${utils.getDateTimeISOString()}`, chalk.green(`Réception de l'url du fichier kml SkydiverId`));
} else {
console.log(`${utils.getDateTimeISOString()}`, chalk.red(`Une erreur ${result.errors.code} '${result.errors.type}' est survenue lors de la réception de l'url du fichier kml SkydiverId : ${result.errors.name} ${result.errors.message}`));
}
if (result.url !== undefined) {
console.log(chalk.green(result.url));
} else {
console.log(chalk.red('result.url is undefined'));
}
return res.json({ file: file.toJSONForJump() });
}).catch(next);
return file.save().then(function () {
Jump.updateOne({_id: req.jump._id}, {files: files}).then(function () {
utils.fetchSkydiverIdApi(`jump/${req.jump.x2data.id}/kml`, {}).then(result => {
if (result.errors === undefined) {
console.log(`${utils.getDateTimeISOString()}`, chalk.green(`Réception de l'url du fichier kml SkydiverId`));
} else {
console.log(`${utils.getDateTimeISOString()}`, chalk.red(`Une erreur ${result.errors.code} '${result.errors.type}' est survenue lors de la réception de l'url du fichier kml SkydiverId : ${result.errors.name} ${result.errors.message}`));
}
if (result.url !== undefined) {
console.log(result.url);
} else {
console.log('result.url is undefined');
}
return res.json({ file: file.toJSONForJump() });
}).catch(next);
}).catch(next);
}).catch(next);
*/
}).catch(next);
});
/**
* update a jump
*/
router.put('/:jump', auth.required, function (req, res, next) {
Promise.all([
req.payload ? User.findById(req.payload.id) : null
]).then(function (results) {
var user = results[0];
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
if (req.jump.author._id.toString() !== req.payload.id.toString()) {
return res.sendStatus(403);
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;
@@ -333,14 +606,14 @@ router.put('/:jump', auth.required, function (req, res, next) {
router.delete('/:jump', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
if (req.jump.author._id.toString() === req.payload.id.toString()) {
return req.jump.remove().then(function () {
return res.sendStatus(204);
});
} else {
return res.sendStatus(403);
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
}).catch(next);
});
-64
View File
@@ -1,64 +0,0 @@
var router = require('express').Router(),
mongoose = require('mongoose'),
Metal = mongoose.model('Metal');
const auth = require('../auth');
// Preload metal objects on routes with ':code'
router.param('code', function (req, res, next, code) {
Metal.findOne({ code: code })
.then(function (metal) {
if (!metal) {
return res.sendStatus(404);
}
req.metal = metal;
return next();
}).catch(next);
});
router.get('/', auth.required, function (req, res, next) {
var query = {};
var limit = 20;
var 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.code !== 'undefined') {
query.code = req.query.code;
}
if (typeof req.query.color !== 'undefined') {
query.color = req.query.color;
}
if (typeof req.query.ordering !== 'undefined') {
query.ordering = req.query.ordering;
}
if (typeof req.query.title !== 'undefined') {
query.title = req.query.title;
}
Promise.all([
Metal.find(query)
.limit(Number(limit))
.skip(Number(offset))
.exec(),
Metal.count(query).exec()
]).then(function (results) {
var metals = results[0];
var metalsCount = results[1];
return res.json({
metals: metals.map(function (metal) {
return metal.toJSONFor();
}),
metalsCount: metalsCount
});
}).catch(next);
});
// return a metal
router.get('/:code', auth.required, function (req, res, next) {
return res.json({ metal: req.metal.toJSONFor() });
});
module.exports = router;
+285
View File
@@ -0,0 +1,285 @@
var router = require('express').Router(),
mongoose = require('mongoose'),
Jump = mongoose.model('Jump'),
User = mongoose.model('User');
const auth = require('../auth'),
queries = require('../queries'),
utils = require('../utils');
router.get('/aeronefs', auth.required, function (req, res, next) {
User.findById(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;
}
Promise.all([
Jump.find({})
.limit(1)
.skip(0)
.sort({ numero: 'desc' })
.populate('author')
.populate('files')
.populate('x2data')
.exec(),
Jump.aggregate(queries.getAeronefsByImatQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec(),
Jump.aggregate(queries.getAeronefsByImatByYearQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec()
]).then(function (results) {
if (results[0].length) {
let lastjump = results[0][0].toJSONFor(user);
let aeronefsByImat = results[1].map(function (data) {
return { aeronef: data._id.aeronef, imat: data._id.imat, count: data.count };
});
let aeronefsByImatByYear = results[2].map(function (data) {
return {
aeronef: data._id.aeronef,
imat: data._id.imat,
year: data._id.year,
count: data.count
};
});
return res.json({
aeronefsByImat: aeronefsByImat,
aeronefsByImatByYear: aeronefsByImatByYear,
lastjump: lastjump
});
} else {
return res.status(422).json({ errors: { lastjump: "Aucun saut enregistré pour le moment" } });
}
}).catch(next);
}).catch(next);
});
router.get('/canopies', auth.required, function (req, res, next) {
User.findById(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;
}
Promise.all([
Jump.find({})
.limit(1)
.skip(0)
.sort({ numero: 'desc' })
.populate('author')
.populate('files')
.populate('x2data')
.exec(),
Jump.aggregate(queries.getCanopiesBySizeQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec(),
Jump.aggregate(queries.getCanopiesBySizeByYearQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec(),
Jump.aggregate(queries.getCanopiesBySizeByModelQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec(),
Jump.aggregate(queries.getCanopiesBySizeByModelByYearQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec()
]).then(function (results) {
if (results[0].length) {
let lastjump = results[0][0].toJSONFor(user);
let canopiesBySize = results[1].map(function (data) {
return { taille: data._id.taille, count: data.count };
});
let canopiesBySizeByYear = results[2].map(function (data) {
return {
taille: data._id.taille,
year: data._id.year,
count: data.count
};
});
let canopiesBySizeByModel = results[3].map(function (data) {
return {
taille: data._id.taille,
voile: data._id.voile,
count: data.count
};
});
let canopiesBySizeByModelByYear = results[4].map(function (data) {
return {
taille: data._id.taille,
voile: data._id.voile,
year: data._id.year,
count: data.count
};
});
return res.json({
canopiesBySize: canopiesBySize,
canopiesBySizeByYear: canopiesBySizeByYear,
canopiesBySizeByModel: canopiesBySizeByModel,
canopiesBySizeByModelByYear: canopiesBySizeByModelByYear,
lastjump: lastjump
});
} else {
return res.status(422).json({ errors: { lastjump: "Aucun saut enregistré pour le moment" } });
}
}).catch(next);
}).catch(next);
});
router.get('/dropzones', auth.required, function (req, res, next) {
User.findById(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;
}
Promise.all([
Jump.find({})
.limit(1)
.skip(0)
.sort({ numero: 'desc' })
.populate('author')
.populate('files')
.populate('x2data')
.exec(),
Jump.aggregate(queries.getDropZonesByOaciQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec(),
Jump.aggregate(queries.getDropZonesByOaciByYearQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec()
]).then(function (results) {
if (results[0].length) {
let lastjump = results[0][0].toJSONFor(user);
let dropZonesByOaci = results[1].map(function (data) {
return { lieu: data._id.lieu, oaci: data._id.oaci, count: data.count };
});
let dropZonesByOaciByYear = results[2].map(function (data) {
return {
lieu: data._id.lieu,
oaci: data._id.oaci,
year: data._id.year,
count: data.count
};
});
return res.json({
dropZonesByOaci: dropZonesByOaci,
dropZonesByOaciByYear: dropZonesByOaciByYear,
lastjump: lastjump
});
} else {
return res.status(422).json({ errors: { lastjump: "Aucun saut enregistré pour le moment" } });
}
}).catch(next);
}).catch(next);
});
router.get('/jumps', auth.required, function (req, res, next) {
User.findById(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;
}
Promise.all([
Jump.find({})
.limit(1)
.skip(0)
.sort({ numero: 'desc' })
.populate('author')
.populate('files')
.populate('x2data')
.exec(),
Jump.aggregate(queries.getJumpByYearsQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec(),
Jump.aggregate(queries.getJumpsByCategoryQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec(),
Jump.aggregate(queries.getJumpsByModuleQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec(),
Jump.aggregate(queries.getJumpsByDateQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec(),
Jump.aggregate(queries.getJumpsByModuleByDateQuery(user._id.toString()))
.skip(Number(offset))
.limit(Number(limit))
.exec()
//utils.fetchSkydiverIdApi('jumps')
]).then(function (results) {
if (results[0].length) {
let lastjump = results[0][0].toJSONFor(user);
let jumpsByYears = results[1].map(function (data) {
return { year: data._id.year, count: data.count };
});
let jumpsByCategory = results[2].map(function (data) {
return { categorie: data._id.categorie, count: data.count };
});
let jumpsByModule = results[3].map(function (data) {
return { categorie: data._id.categorie, module: data._id.module, count: data.count };
});
let jumpsByDate = results[4].map(function (data) {
return { year: data._id.year, month: data._id.month, count: data.count };
});
let jumpsByDateByModule = results[5].map(function (data) {
return {
categorie: data._id.categorie,
module: data._id.module,
year: data._id.year,
month: data._id.month,
count: data.count
};
});
//let jumpsFromSkydiverIdApi = results[6];
return res.json({
jumpsByCategory: jumpsByCategory,
jumpsByDate: jumpsByDate,
jumpsByDateByModule: jumpsByDateByModule,
jumpsByModule: jumpsByModule,
jumpsByYears: jumpsByYears,
//jumpsFromSkydiverIdApi: jumpsFromSkydiverIdApi,
lastjump: lastjump
});
} else {
return res.status(422).json({ errors: { lastjump: "Aucun saut enregistré pour le moment" } });
}
}).catch(next);
}).catch(next);
});
module.exports = router;
-133
View File
@@ -1,133 +0,0 @@
var router = require('express').Router(),
mongoose = require('mongoose'),
Metal = mongoose.model('Metal'),
Price = mongoose.model('Price'),
Currency = mongoose.model('Currency');
const auth = require('../auth'),
utils = require('../utils'),
chalk = require('chalk');
// Preload metal objects on routes with ':metal'
router.param('metal', function (req, res, next, code) {
Metal.findOne({ code: code })
.then(function (metal) {
if (!metal) {
return res.sendStatus(404);
}
req.metal = metal.code;
return next();
}).catch(next);
});
// Preload currency objects on routes with ':currency'
router.param('currency', function (req, res, next, code) {
req.currency = code;
Currency.findOne({ code: code })
.then(function (currency) {
if (!currency) {
return res.sendStatus(404);
}
req.currency = currency.code;
return next();
}).catch(next);
});
router.get('/', auth.required, function (req, res, next) {
var query = {};
var limit = 20;
var offset = 0;
const fields = ['metal', 'currency', 'exchange', 'symbol'];
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
fields.forEach(field => {
if (typeof req.query[field] !== 'undefined') {
query[field] = req.query[field];
}
});
Metal.find({})
.limit(Number(limit))
.skip(Number(offset))
.sort({ ordering: 1 })
.exec()
.then(metals => {
const currency = 'EUR';
Promise.all(
metals.map(metal => Price.findOne({ metal: metal.code, currency: currency }))
).then(results => {
let queries$ = [];
var prices = results.map((price, index) => {
if (!price) {
price = new Price({ metal: metals[index].code, currency: currency });
}
const now = new Date().getTime();
const diff = parseInt(((now - price.timestamp) / 1000));
if (diff >= 50) {
queries$.push(utils.fetchApi(price, res).then(result => {
if (result.errors === undefined) {
price.overwrite(result);
price.save();
console.log(`${utils.getDateTimeISOString()}`, chalk.green(`${price.metal} | ${price.currency} - Sauvegarde du prix spot`), chalk.magenta(price.price));
} else {
console.log(`${utils.getDateTimeISOString()}`, chalk.red(`${price.metal} | ${price.currency} - Une erreur ${result.errors.code} '${result.errors.type}' est survenue : ${result.errors.name} ${result.errors.message}`));
}
return price;
}));
} else {
console.log(`${utils.getDateTimeISOString()}`, chalk.cyan(`${price.metal} | ${price.currency} - Utilisation du prix spot`), chalk.magenta(price.price));
}
return price;
});
if (queries$.length) {
Promise.all(
queries$
).then(() => {
return res.json({
prices: prices,
pricesCount: prices.length
});
}).catch(next);
} else {
return res.json({
prices: prices,
pricesCount: results[2]
});
}
}).catch(next);
}
);
});
router.get('/:metal/:currency', auth.required, function (req, res, next) {
Price.findOne({ metal: req.metal, currency: req.currency })
.then(function (price) {
if (!price) {
price = new Price({ metal: req.metal, currency: req.currency });
}
const now = new Date().getTime();
const diff = parseInt(((now - price.timestamp) / 1000));
if (diff >= 50) {
utils.fetchApi(price, res).then(result => {
if (result.errors === undefined) {
price.overwrite(result);
return price.save().then(function (data) {
console.log(`${utils.getDateTimeISOString()}`, chalk.green(`${data.metal} | ${data.currency} - Enregistrement du prix spot`), chalk.magenta(data.price));
return res.json({ price: data.toJSONFor() });
});
} else {
console.log(`${utils.getDateTimeISOString()}`, chalk.red(`${price.metal} | ${price.currency} - Une erreur ${result.errors.code} '${result.errors.type}' est survenue : `), chalk.red(`${result.errors.name} ${result.errors.message}`));
return res.json({ price: price });
}
});
} else {
console.log(`${utils.getDateTimeISOString()}`, chalk.cyan(`${price.metal} | ${price.currency} - Utilisation du prix stocké`), chalk.magenta(price.price));
return res.json({ price: price.toJSONFor() });
}
}).catch(next);
});
module.exports = router;
-238
View File
@@ -1,238 +0,0 @@
var router = require('express').Router(),
mongoose = require('mongoose'),
Product = mongoose.model('Product'),
User = mongoose.model('User'),
Metal = mongoose.model('Metal');
const auth = require('../auth');
// Preload product objects on routes with ':product'
router.param('product', function (req, res, next, slug) {
Product.findOne({ slug: slug })
.populate('author')
.populate('metal')
.then(function (product) {
if (!product) {
return res.sendStatus(404);
}
req.product = product;
return next();
}).catch(next);
});
router.get('/', auth.required, function (req, res, next) {
var query = {};
var limit = 20;
var 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') {
const rgx = new RegExp(`.*${req.query.title}.*`);
query = {
$or: [
{ title: { $regex: rgx, $options: "i" } },
{ slug: { $regex: rgx, $options: "i" } },
],
}
}
Promise.all([
req.query.author ? User.findOne({ username: req.query.author }) : null,
req.query.favorited ? User.findOne({ username: req.query.favorited }) : null
]).then(function (users) {
var author = users[0];
var favoriter = users[1];
if (author) {
query.author = author._id;
}
if (favoriter) {
query._id = { $in: favoriter.favorites };
} else if (req.query.favorited) {
query._id = { $in: [] };
}
return Promise.all([
Product.find(query)
.limit(Number(limit))
.skip(Number(offset))
.sort({ ordering: 'asc' })
.populate('author')
.populate('metal')
.exec(),
Product.count(query).exec(),
req.payload ? User.findById(req.payload.id) : null
]).then(function (results) {
var products = results[0];
var productsCount = results[1];
var user = results[2];
return res.json({
products: products.map(function (product) {
return product.toJSONFor(user);
}),
productsCount: productsCount
});
});
}).catch(next);
});
router.get('/feed', auth.required, function (req, res, next) {
var limit = 20;
var offset = 0;
if (typeof req.query.limit !== 'undefined') {
limit = req.query.limit;
}
if (typeof req.query.offset !== 'undefined') {
offset = req.query.offset;
}
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
}
var query = { author: { $in: user.following } };
Promise.all([
Product.find(query)
.limit(Number(limit))
.skip(Number(offset))
.populate('author')
.populate('metal')
.exec(),
Product.count(query)
]).then(function (results) {
var products = results[0];
var productsCount = results[1];
return res.json({
products: products.map(function (product) {
return product.toJSONFor(user);
}),
productsCount: productsCount
});
}).catch(next);
});
});
router.post('/', auth.required, function (req, res, next) {
Promise.all([
req.payload ? User.findById(req.payload.id) : null,
Metal.findOne({ code: req.body.product.metal.code }).exec(),
Product
.find({}).select('ordering')
.sort({"ordering" : -1}).limit(1)
.exec()
]).then(function (results) {
var user = results[0];
var metal = results[1];
var ordering = (results[2][0].ordering + 1);
if (!user) {
return res.sendStatus(401);
}
var product = new Product(req.body.product);
product.author = user;
product.metal = metal;
product.ordering = ordering;
return product.save().then(function () {
return res.json({ product: product.toJSONFor(user) });
});
}).catch(next);
});
// return a product
router.get('/:product', auth.optional, function (req, res, next) {
Promise.all([
req.payload ? User.findById(req.payload.id) : null,
req.product.populate('author'),
req.product.populate('metal')
]).then(function (results) {
var user = results[0];
return res.json({ product: req.product.toJSONFor(user) });
}).catch(next);
});
router.put('/:product', auth.required, function (req, res, next) {
Promise.all([
req.payload ? User.findById(req.payload.id) : null,
Metal.findOne({ code: req.body.product.metal.code }).exec()
]).then(function (results) {
var user = results[0];
var metal = results[1];
if (!user) {
return res.sendStatus(401);
}
if (req.product.author._id.toString() !== req.payload.id.toString()) {
return res.sendStatus(403);
}
if (typeof req.body.product.title !== 'undefined') {
req.product.title = req.body.product.title;
}
if (typeof req.body.product.prime_achat !== 'undefined') {
req.product.prime_achat = req.body.product.prime_achat;
}
if (typeof req.body.product.prime_vente !== 'undefined') {
req.product.prime_vente = req.body.product.prime_vente;
}
if (typeof req.body.product.poids !== 'undefined') {
req.product.poids = req.body.product.poids;
}
req.product.metal = metal;
return req.product.save().then(function (product) {
return res.json({ product: product.toJSONFor(user) });
});
}).catch(next);
});
// delete product
router.delete('/:product', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
}
if (req.product.author._id.toString() === req.payload.id.toString()) {
return req.product.remove().then(function () {
return res.sendStatus(204);
});
} else {
return res.sendStatus(403);
}
}).catch(next);
});
// Favorite an product
router.post('/:product/favorite', auth.required, function (req, res, next) {
var productId = req.product._id;
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
}
return user.favorite(productId).then(function () {
return req.product.updateFavoriteCount().then(function (product) {
return res.json({ product: product.toJSONFor(user) });
});
});
}).catch(next);
});
// Unfavorite an product
router.delete('/:product/favorite', auth.required, function (req, res, next) {
var productId = req.product._id;
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
}
return user.unfavorite(productId).then(function () {
return req.product.updateFavoriteCount().then(function (product) {
return res.json({ product: product.toJSONFor(user) });
});
});
}).catch(next);
});
module.exports = router;
+5 -5
View File
@@ -15,7 +15,7 @@ router.param('username', function (req, res, next, username) {
}).catch(next);
});
router.get('/:username', auth.optional, function (req, res, next) {
router.get('/:username', auth.optional, function (req, res) {
if (req.payload) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
@@ -29,11 +29,11 @@ router.get('/:username', auth.optional, function (req, res, next) {
});
router.post('/:username/follow', auth.required, function (req, res, next) {
var profileId = req.profile._id;
let profileId = req.profile._id;
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
return user.follow(profileId).then(function () {
return res.json({ profile: req.profile.toProfileJSONFor(user) });
@@ -42,11 +42,11 @@ router.post('/:username/follow', auth.required, function (req, res, next) {
});
router.delete('/:username/follow', auth.required, function (req, res, next) {
var profileId = req.profile._id;
let profileId = req.profile._id;
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
return user.unfollow(profileId).then(function () {
return res.json({ profile: req.profile.toProfileJSONFor(user) });
+117 -10
View File
@@ -1,19 +1,34 @@
var router = require('express').Router(),
mongoose = require('mongoose'),
QCM = mongoose.model('QCM'),
Qcm = mongoose.model('Qcm'),
QcmCategory = mongoose.model('QcmCategory'),
QcmQuestion = mongoose.model('QcmQuestion'),
QcmChoice = mongoose.model('QcmChoice'),
User = mongoose.model('User');
const auth = require('../auth');
// Preload qcm objects on routes with ':type'
router.param('type', function (req, res, next, type) {
QCM.findOne({ name: type })
Qcm.findOne({ name: type })
.populate('categories')
.then(function (qcm) {
.then(qcm => {
if (!qcm) {
return res.sendStatus(404);
return res.status(404).json({ errors: { "Not Found": "Le QCM est introuvable ou inexistant." } });
}
req.qcm = qcm;
return next();
Promise.all(
req.qcm.categories.map(category => {
return category.populate('questions').then(() => {
return Promise.all(
category.questions.map(question => question.populate('choices'))
).then(() => {
return category;
}).catch(next);
});
})
).then(() => {
return next();
}).catch(next);
}).catch(next);
});
@@ -24,9 +39,9 @@ router.get('/', auth.required, function (req, res, next) {
Promise.all([
req.payload ? User.findById(req.payload.id) : null
]).then(function (results) {
var user = results[0];
let user = results[0];
if (!user) {
return res.sendStatus(401);
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
return res.json({ qcm: [] });
}).catch(next);
@@ -35,16 +50,108 @@ router.get('/', auth.required, function (req, res, next) {
/**
* return a qcm
*/
router.get('/:type', auth.required, function (req, res, next) {
router.get('/type/:type', auth.required, function (req, res, next) {
Promise.all([
req.payload ? User.findById(req.payload.id) : null
]).then(function (results) {
var user = results[0];
let user = results[0];
if (!user) {
return res.sendStatus(401);
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
return res.json({ qcm: req.qcm.toJSONFor() });
}).catch(next);
});
/**
* save an array of qcm question choice
*/
router.post('/choices/', auth.required, function (req, res, next) {
Promise.all([
req.payload ? User.findById(req.payload.id) : null,
QcmQuestion
.findOne({num: req.body.question.num})
.populate('choices')
.exec()
]).then(async function (results) {
const user = results[0];
//let numero = (results[1][0].numero + 1);
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
if (user.role !== 'Admin') {
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
const question = results[1];
if (!question) {
return res.status(422).json({ errors: { question: "question introuvable" } });
}
let choices = [];
Promise.all(
req.body.question.choices.map(data => {
const choiceId = new mongoose.Types.ObjectId();
const choice = new QcmChoice({ _id: choiceId, index: data.index, libelle: data.libelle, correct: data.correct});
choices.push(choiceId);
return choice.save();
})
).then(function () {
question.choices = [...choices];
question.save().then(function () {
QcmQuestion
.findOne({num: req.body.question.num})
.populate('choices')
.exec()
.then(function (question) {
return res.json({ question: question.toJSONFor() });
}).catch(next);
}).catch(next);
}).catch(next);
}).catch(next);
});
/**
* save an array of qcm category questions
*/
router.post('/questions/', auth.required, function (req, res, next) {
Promise.all([
req.payload ? User.findById(req.payload.id) : null,
QcmCategory
.findOne({num: req.body.category.num})
.populate('questions')
.exec()
]).then(async function (results) {
const user = results[0];
//let numero = (results[1][0].numero + 1);
if (!user) {
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
if (user.role !== 'Admin') {
return res.status(403).json({ errors: { "Forbidden": "Vous ne disposez pas des autorisations suffisantes" } });
}
const category = results[1];
if (!category) {
return res.status(422).json({ errors: { category: "catégorie introuvable" } });
}
let questions = [];
Promise.all(
req.body.category.questions.map(data => {
const questionId = new mongoose.Types.ObjectId();
const question = new QcmQuestion({ _id: questionId, num: data.num, libelle: data.libelle, choices: []});
questions.push(questionId);
return question.save();
})
).then(function () {
category.questions = [...questions];
category.save().then(function () {
QcmCategory
.findOne({num: req.body.category.num})
.populate('questions')
.exec()
.then(function (category) {
return res.json({ category: category.toJSONFor() });
}).catch(next);
}).catch(next);
}).catch(next);
}).catch(next);
});
module.exports = router;
+3 -3
View File
@@ -7,7 +7,7 @@ const passport = require('passport'),
router.get('/user', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
return res.json({ user: user.toAuthJSON() });
}).catch(next);
@@ -16,7 +16,7 @@ router.get('/user', auth.required, function (req, res, next) {
router.put('/user', auth.required, function (req, res, next) {
User.findById(req.payload.id).then(function (user) {
if (!user) {
return res.sendStatus(401);
return res.status(401).json({ errors: { "Unauthorized": "autentification requise" } });
}
if (typeof req.body.user.username !== 'undefined') {
user.username = req.body.user.username;
@@ -96,7 +96,7 @@ router.get('/authenticate', function (req, res, next) {
})(req, res, next);
});
router.post('/users', function (req, res, next) {
var user = new User();
let user = new User();
if (typeof req.body.user.username !== 'undefined') {
user.username = req.body.user.username;
} else {
+507
View File
@@ -0,0 +1,507 @@
const queries = {
getJumpsByCategoryQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$group': {
'_id': {
'categorie': '$categorie'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
return query;
},
getJumpsByDateQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$project': {
'_id': 0,
'year': {
'$year': '$date'
},
'month': {
'$month': '$date'
}
}
}, {
'$group': {
'_id': {
'year': '$year',
'month': '$month'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
return query;
},
getJumpsByModuleByDateQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$project': {
'_id': 0,
'module': 1,
'categorie': 1,
'year': {
'$year': '$date'
},
'month': {
'$month': '$date'
}
}
}, {
'$group': {
'_id': {
'module': '$module',
'categorie': '$categorie',
'year': '$year',
'month': '$month'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
return query;
},
getJumpsByModuleQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$project': {
'_id': 0,
'categorie': 1,
'module': 1
}
}, {
'$group': {
'_id': {
'categorie': '$categorie',
'module': '$module'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
return query;
},
getJumpByYearsQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$project': {
'_id': 0,
'year': {
'$year': '$date'
}
}
}, {
'$group': {
'_id': {
'year': '$year'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
return query;
},
getAeronefsByImatQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$group': {
'_id': {
'aeronef': '$aeronef',
'imat': '$imat'
},
'count': {
'$sum': 1
}
}
}, {
'$sort':
{
'count': -1
},
}
];
return query;
},
getAeronefsByImatByYearQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$project': {
'_id': 0,
'aeronef': 1,
'imat': 1,
'year': {
'$year': '$date'
}
}
}, {
'$group': {
'_id': {
'aeronef': '$aeronef',
'imat': '$imat',
'year': '$year'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
return query;
},
getCanopiesBySizeQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$group': {
'_id': {
'taille': '$taille'
},
'count': {
'$sum': 1
}
}
}, {
'$sort':
{
'_id': 1
},
}
];
return query;
},
getCanopiesBySizeByYearQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$project': {
'_id': 0,
'taille': 1,
'year': {
'$year': '$date'
}
}
}, {
'$group': {
'_id': {
'taille': '$taille',
'year': '$year'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
return query;
},
getCanopiesBySizeByModelQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$group': {
'_id': {
'taille': '$taille',
'voile': '$voile'
},
'count': {
'$sum': 1
}
}
}, {
'$sort':
{
'_id': 1
},
}
];
return query;
},
getCanopiesBySizeByModelByYearQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$project': {
'_id': 0,
'voile': 1,
'taille': 1,
'year': {
'$year': '$date'
}
}
}, {
'$group': {
'_id': {
'taille': '$taille',
'voile': '$voile',
'year': '$year'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
return query;
},
getDropZonesByOaciQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$group': {
'_id': {
'lieu': '$lieu',
'oaci': '$oaci'
},
'count': {
'$sum': 1
}
}
}, {
'$sort':
{
'_id': 1
},
}
];
return query;
},
getDropZonesByOaciByYearQuery: (userId) => {
let query = [
{
'$match': {
'$expr': {
'$eq': [ '$author' , { '$toObjectId': userId } ]
}
}
}, {
'$project': {
'_id': 0,
'lieu': 1,
'oaci': 1,
'year': {
'$year': '$date'
}
}
}, {
'$group': {
'_id': {
'lieu': '$lieu',
'oaci': '$oaci',
'year': '$year'
},
'count': {
'$sum': 1
}
}
}, {
'$sort': {
'_id': 1
}
}
];
return query;
},
getJumpsByDayQuery: (userId, dateRangeStart = null, dateRangeEnd = null) => {
if (dateRangeStart === null) {
dateRangeStart = '1970-01-01 00:00:00';
}
if (dateRangeEnd === null) {
const year = new Date().getFullYear();
dateRangeEnd = `${year}-12-31 23:59:59`;
}
let query = [
{
$match: {
$expr: {
$and: [
{
$eq: [ '$author' , { '$toObjectId': userId } ]
},
{
$gte: ['$date', new Date(dateRangeStart)]
},
{
$lte: ['$date', new Date(dateRangeEnd)]
}
]
}
}
}, {
$project: {
_id: 1,
slug: "$slug",
numero: "$numero",
date: "$date",
year: {
$year: "$date"
},
month: {
$month: "$date"
},
day: {
$dayOfMonth: "$date"
}
}
},
{
$group: {
_id: {
year: "$year",
month: "$month",
day: "$day"
},
jumps: {
$addToSet: {
_id: "$_id",
numero: "$numero",
slug: "$slug",
date: "$date"
}
},
count: {
$sum: 1
}
}
},
{
$sort: {
_id: 1,
}
},
{
$project: {
_id: 0,
jumps: 1,
count: 1
}
}
];
return query;
}
};
module.exports = queries;
+53 -5
View File
@@ -1,16 +1,13 @@
const chalk = require('chalk');
const utils = {
getDateString: () => {
let today = new Date();
let dateNow = today.toLocaleDateString();
return `${dateNow}`;
},
getTimeString: () => {
let today = new Date();
let timeNow = today.toLocaleTimeString();
return `${timeNow}`;
},
getDateTimeString: (delimiter = true) => {
@@ -19,7 +16,6 @@ const utils = {
if (delimiter) {
dateString = `[${dateString}]`;
}
return dateString;
},
getDateTimeISOString: (delimiter = true) => {
@@ -28,8 +24,60 @@ const utils = {
if (delimiter) {
dateString = `[${dateString}]`;
}
return dateString;
},
async fetchSkydiverIdApi(path, query) {
let limit = 50;
let offset = 0;
let args = '';
if (typeof query.limit !== 'undefined') {
limit = query.limit;
}
if (typeof query.offset !== 'undefined') {
offset = ((query.offset/limit)+1);
}
if (offset > 1) {
args += `&page=${offset}`;
}
if (typeof query.dateRangeStart !== 'undefined' && typeof query.dateRangeEnd !== 'undefined') {
args += `&filter[and][0][date][gte]=${query.dateRangeStart}`;
args += `&filter[and][0][date][lte]=${query.dateRangeEnd}`;
}
try {
let url = `${process.env.SKYDIVERID_API_URL}/${path}`;
if (typeof query.limit !== 'undefined') {
url += `?per-page=${limit}${args}`;
}
/* url pour provoquer une erreur en dev : url = `https://www.goldapi.ioppppp/api/${price.metal}/${price.currency}`; */
let options = {
method: 'GET',
headers: {
'Authorization': `Bearer ${process.env.SKYDIVERID_API_TOKEN}`,
'Content-Type': 'application/json'
},
redirect: 'follow'
};
/* Pour tester le retour d'erreur : return { errors: { name: 'error name', message: 'error message', type: 'TYPE', code: 'CODE' } }; */
//const response = await fetch(url, options);
return fetch(url, options).then(function (response) {
if (response.status >= 200 && response.status < 400) {
console.log(`${utils.getDateTimeISOString()}`, chalk.green(`Réception des sauts via SkydiverId API`), `${response.status} ${response.statusText}`);
const data = response.json();
console.log(data);
return data;
} else {
console.log(`${utils.getDateTimeISOString()}`, chalk.red(`Erreur ${response.status} ${response.statusText}`));
return { errors: { name: response.statusText, message: `Une erreur ${response.status} '${response.statusText}' est survenue lors de la récupération des sauts via SkydiverId API`, type: 'API Error', code: response.status } };
}
})
.catch(error => {
console.log(`${utils.getDateTimeISOString()}`, chalk.red(`A fetchSkydiverIdApi error occured ${error.code} ${error.type}`));
return { errors: { name: error.name, message: `A fetchSkydiverIdApi error occured : ${error.message}`, type: error.type, code: error.code } };
});
} catch (error) {
console.log(`${utils.getDateTimeISOString()}`, chalk.red(`fetchSkydiverIdApi error`));
return { errors: { name: error.name, message: error.message, type: error.type, code: error.code } };
}
}
};