---|main| Initial commit
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
# Editor configuration, see http://editorconfig.org
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.md]
|
||||
max_line_length = off
|
||||
trim_trailing_whitespace = false
|
||||
@@ -0,0 +1,16 @@
|
||||
APP_ENV="development"
|
||||
NODE_ENV="development"
|
||||
DEBUG=false
|
||||
MONGODB_URI="mongodb://localhost:27017/headupdb"
|
||||
SERVER_PORT="3200"
|
||||
SECRET="$2b$10$sMuV/fTCGm9CJGamPFvvte"
|
||||
SENDGRID_API_KEY="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"
|
||||
SENDGRID_FROM_MAIL="contact@rampeur.fr"
|
||||
SENDGRID_TO_MAIL="rampeur@gmail.com"
|
||||
AUTHORIZATION_PREFIX="Api-Key"
|
||||
GOLDAPI_URL="https://www.goldapi.io/api"
|
||||
GOLDAPI_TOKEN="goldapi-akasnfrlfiqv0xw-io"
|
||||
COUCHDB_URL="http://couchdb.unespace.com"
|
||||
COUCHDB_DATABASE="headupdb"
|
||||
COUCHDB_DESIGN="headup_app"
|
||||
COUCHDB_CREDENTIAL="cmFtcGV1cjpES3hwMjRQUw=="
|
||||
@@ -0,0 +1,16 @@
|
||||
APP_ENV="development"
|
||||
NODE_ENV="development"
|
||||
DEBUG=true
|
||||
MONGODB_URI="mongodb://localhost:27017/headupdb"
|
||||
SERVER_PORT="3200"
|
||||
SECRET="$2b$10$7LPCMF6razIF744f3k3dLu"
|
||||
SENDGRID_API_KEY="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"
|
||||
SENDGRID_FROM_MAIL="contact@rampeur.fr"
|
||||
SENDGRID_TO_MAIL="rampeur@gmail.com"
|
||||
AUTHORIZATION_PREFIX="Api-Key"
|
||||
GOLDAPI_URL="https://www.goldapi.io/api"
|
||||
GOLDAPI_TOKEN="goldapi-akasnfrlfiqv0xw-io"
|
||||
COUCHDB_URL="http://couchdb.unespace.com"
|
||||
COUCHDB_DATABASE="headupdb"
|
||||
COUCHDB_DESIGN="headup_app"
|
||||
COUCHDB_CREDENTIAL="cmFtcGV1cjpES3hwMjRQUw=="
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
APP_ENV="local"
|
||||
NODE_ENV="development"
|
||||
DEBUG=false
|
||||
MONGODB_URI="mongodb://localhost:27017/headupdb"
|
||||
SERVER_PORT="3200"
|
||||
SECRET="$2b$10$2.JkQCRUa3fXESy/WyKVWO"
|
||||
SENDGRID_API_KEY="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"
|
||||
SENDGRID_FROM_MAIL="contact@rampeur.fr"
|
||||
SENDGRID_TO_MAIL="rampeur@gmail.com"
|
||||
AUTHORIZATION_PREFIX="Api-Key"
|
||||
GOLDAPI_URL="https://www.goldapi.io/api"
|
||||
GOLDAPI_TOKEN="goldapi-akasnfrlfiqv0xw-io"
|
||||
COUCHDB_URL="http://couchdb.unespace.com"
|
||||
COUCHDB_DATABASE="headupdb"
|
||||
COUCHDB_DESIGN="headup_app"
|
||||
COUCHDB_CREDENTIAL="cmFtcGV1cjpES3hwMjRQUw=="
|
||||
@@ -0,0 +1,16 @@
|
||||
APP_ENV="production"
|
||||
NODE_ENV="production"
|
||||
DEBUG=false
|
||||
MONGODB_URI="mongodb://localhost:27017/headupdb"
|
||||
SERVER_PORT="3030"
|
||||
SECRET="$2b$10$t1ma1H6HsGi8tMK4GRH5fu"
|
||||
SENDGRID_API_KEY="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"
|
||||
SENDGRID_FROM_MAIL="contact@rampeur.fr"
|
||||
SENDGRID_TO_MAIL="rampeur@gmail.com"
|
||||
AUTHORIZATION_PREFIX="Api-Key"
|
||||
GOLDAPI_URL="https://www.goldapi.io/api"
|
||||
GOLDAPI_TOKEN="goldapi-akasnfrlfiqv0xw-io"
|
||||
COUCHDB_URL="http://couchdb.unespace.com"
|
||||
COUCHDB_DATABASE="headupdb"
|
||||
COUCHDB_DESIGN="headup_app"
|
||||
COUCHDB_CREDENTIAL="cmFtcGV1cjpES3hwMjRQUw=="
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
.DS_Store
|
||||
|
||||
npm-debug.log*
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
|
||||
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# node-waf configuration
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (http://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directory
|
||||
node_modules
|
||||
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
# Optional REPL history
|
||||
.node_repl_history
|
||||
|
||||
.idea
|
||||
@@ -0,0 +1,118 @@
|
||||
var appEnv = process.env.APP_ENV;
|
||||
if (appEnv == undefined) {
|
||||
appEnv = 'development';
|
||||
}
|
||||
require('dotenv').config({ path: `.env.${appEnv}` });
|
||||
const { promisify } = require('util'),
|
||||
bodyParser = require('body-parser'),
|
||||
chalk = require('chalk'),
|
||||
utils = require('./routes/utils');
|
||||
var express = require('express'),
|
||||
session = require('express-session'),
|
||||
cors = require('cors'),
|
||||
errorhandler = require('errorhandler'),
|
||||
mongoose = require('mongoose'),
|
||||
morgan = require('morgan');
|
||||
|
||||
var isProduction = appEnv === 'production';
|
||||
|
||||
// Create global app object
|
||||
var app = express();
|
||||
|
||||
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)
|
||||
? res.statusCode
|
||||
: undefined
|
||||
|
||||
return status >= 500 ? chalk.red(status)
|
||||
: status >= 429 ? chalk.magenta(status)
|
||||
: status >= 400 ? chalk.yellow(status)
|
||||
: status >= 300 ? chalk.cyan(status)
|
||||
: status >= 200 ? chalk.green(status)
|
||||
: chalk.underline(status);
|
||||
});
|
||||
app.use(morgan('[:date[iso]] ":method :url HTTP/:http-version" :statusColor :res[content-length] ":referrer" ":user-agent" :remote-addr'));
|
||||
app.use(bodyParser.urlencoded({ extended: false }));
|
||||
app.use(bodyParser.json());
|
||||
|
||||
app.use(require('method-override')());
|
||||
app.use(express.static(__dirname + '/public'));
|
||||
|
||||
app.use(session({ secret: 'acapisecret', cookie: { maxAge: 60000 }, resave: false, saveUninitialized: false }));
|
||||
|
||||
if (!isProduction) {
|
||||
app.use(errorhandler());
|
||||
}
|
||||
|
||||
if(isProduction){
|
||||
mongoose.connect(process.env.MONGODB_URI);
|
||||
} else {
|
||||
mongoose.set('strictQuery', true);
|
||||
mongoose.connect(process.env.MONGODB_URI).then(() => {
|
||||
console.log(`${utils.getDateTimeISOString()}`, chalk.green('MongoDB connection has been established successfully'));
|
||||
}).catch(() => {
|
||||
console.log(`${utils.getDateTimeISOString()}`, chalk.red('Unable to connect to the MongoDB database'));
|
||||
});
|
||||
mongoose.set('debug', 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/Metal');
|
||||
require('./models/mongo/Price');
|
||||
require('./models/mongo/Product');
|
||||
*/
|
||||
require('./config/passport');
|
||||
|
||||
app.use(require('./routes'));
|
||||
|
||||
/// catch 404 and forward to error handler
|
||||
app.use(function(req, res, next) {
|
||||
var 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);
|
||||
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);
|
||||
res.json({errors: {
|
||||
message: err.message,
|
||||
error: {},
|
||||
stack: {}
|
||||
}});
|
||||
});
|
||||
}
|
||||
|
||||
const startServer = async () => {
|
||||
const port = process.env.SERVER_PORT || 3200;
|
||||
await promisify(app.listen).bind(app)(port);
|
||||
console.log(`${utils.getDateTimeISOString()}`, chalk.green(`${process.env.APP_ENV} API server listening on port ${port}`));
|
||||
}
|
||||
|
||||
// finally, let's start our server...
|
||||
startServer();
|
||||
@@ -0,0 +1,24 @@
|
||||
module.exports = {
|
||||
"development": {
|
||||
"username": 'jgautier',
|
||||
"password": 'TXhtCj-qJy6CPH-YkHT7p-zHY3nR',
|
||||
"database": 'barrett_aucoffre',
|
||||
"host": '51.68.76.171',
|
||||
"port": 3308,
|
||||
"dialect": 'mysql'
|
||||
},
|
||||
"test": {
|
||||
"username": "root",
|
||||
"password": null,
|
||||
"database": "database_test",
|
||||
"host": "127.0.0.1",
|
||||
"dialect": "mysql"
|
||||
},
|
||||
"production": {
|
||||
"username": "root",
|
||||
"password": null,
|
||||
"database": "database_production",
|
||||
"host": "127.0.0.1",
|
||||
"dialect": "mysql"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
|
||||
const config = {
|
||||
secret: process.env.SECRET || 'acapisecret'
|
||||
};
|
||||
module.exports = config;
|
||||
@@ -0,0 +1,43 @@
|
||||
var bcrypt = require('bcrypt');
|
||||
const passport = require('passport');
|
||||
var LocalStrategy = require('passport-local').Strategy;
|
||||
var HeaderAPIKeyStrategy = require('passport-headerapikey').HeaderAPIKeyStrategy;
|
||||
var mongoose = require('mongoose');
|
||||
var Application = mongoose.model('Application');
|
||||
var User = mongoose.model('User');
|
||||
|
||||
passport.use('headerapikey', new HeaderAPIKeyStrategy(
|
||||
{ header: 'Authorization', prefix: `${process.env.AUTHORIZATION_PREFIX} ` },
|
||||
false,
|
||||
function (apikey, done) {
|
||||
const maskedKey = `${apikey.slice(0, 4)}...${apikey.slice(-4)}`;
|
||||
Application.findOne({ maskedkey: maskedKey })
|
||||
.populate('author')
|
||||
.then(function (application) {
|
||||
if (!application) {
|
||||
return done({message: "Application can't be found.", status: 404}, false, false);
|
||||
//return done(null, false, false);
|
||||
}
|
||||
return {app: application, prom: Promise.resolve(bcrypt.compare(apikey, application.apikey))};
|
||||
}).then(function (res) {
|
||||
res.prom.then(function (valid) {
|
||||
if (!valid) {
|
||||
return done(null, false, {app: res.app, valid: valid});
|
||||
}
|
||||
return done(null, res.app, valid);
|
||||
});
|
||||
}).catch(done);
|
||||
}
|
||||
));
|
||||
|
||||
passport.use('local', new LocalStrategy({
|
||||
usernameField: 'user[email]',
|
||||
passwordField: 'user[password]'
|
||||
}, function (email, password, done) {
|
||||
User.findOne({ email: email }).then(function (user) {
|
||||
if (!user || !user.validPassword(password)) {
|
||||
return done(null, false, { errors: { 'email ou mot de passe': 'invalide' } });
|
||||
}
|
||||
return done(null, user);
|
||||
}).catch(done);
|
||||
}));
|
||||
@@ -0,0 +1,34 @@
|
||||
var mongoose = require('mongoose');
|
||||
var User = mongoose.model('User');
|
||||
var slug = require('slug');
|
||||
|
||||
var AeronefSchema = new mongoose.Schema({
|
||||
slug: { type: String, lowercase: true, unique: true },
|
||||
aeronef: String,
|
||||
imat: String,
|
||||
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
|
||||
}, {timestamps: true, toJSON: {virtuals: true}});
|
||||
|
||||
AeronefSchema.pre('validate', function (next) {
|
||||
if (!this.slug) {
|
||||
this.slugify();
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
AeronefSchema.methods.slugify = function () {
|
||||
this.slug = slug(`${this.aeronef} ${this.imat}`) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36);
|
||||
};
|
||||
|
||||
AeronefSchema.methods.toJSONFor = function(user){
|
||||
return {
|
||||
slug: this.slug,
|
||||
aeronef: this.aeronef,
|
||||
imat: this.imat,
|
||||
createdAt: this.createdAt,
|
||||
updatedAt: this.updatedAt,
|
||||
author: this.author.toProfileJSONFor(user)
|
||||
};
|
||||
};
|
||||
|
||||
mongoose.model('Aeronef', AeronefSchema);
|
||||
@@ -0,0 +1,51 @@
|
||||
var mongoose = require('mongoose');
|
||||
var uniqueValidator = require('mongoose-unique-validator');
|
||||
var slug = require('slug');
|
||||
|
||||
var ApplicationSchema = new mongoose.Schema({
|
||||
apikey: String,
|
||||
maskedkey: String,
|
||||
slug: { type: String, lowercase: true, unique: true },
|
||||
title: String,
|
||||
description: String,
|
||||
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
|
||||
}, { timestamps: true, toJSON: { virtuals: true } });
|
||||
|
||||
ApplicationSchema.plugin(uniqueValidator, { message: 'is already taken' });
|
||||
|
||||
ApplicationSchema.pre('validate', function (next) {
|
||||
if (!this.slug) {
|
||||
this.slugify();
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
ApplicationSchema.methods.slugify = function () {
|
||||
this.slug = slug(this.title) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36);
|
||||
};
|
||||
|
||||
ApplicationSchema.methods.toJSONFor = function (user) {
|
||||
return {
|
||||
maskedkey: this.maskedkey,
|
||||
slug: this.slug,
|
||||
title: this.title,
|
||||
description: this.description,
|
||||
createdAt: this.createdAt,
|
||||
updatedAt: this.updatedAt,
|
||||
author: this.author.toProfileJSONFor(user)
|
||||
};
|
||||
};
|
||||
|
||||
ApplicationSchema.methods.toAuthJSON = function () {
|
||||
return {
|
||||
maskedkey: this.maskedkey,
|
||||
slug: this.slug,
|
||||
title: this.title,
|
||||
description: this.description,
|
||||
createdAt: this.createdAt,
|
||||
updatedAt: this.updatedAt,
|
||||
author: this.author.toJSONFor()
|
||||
};
|
||||
};
|
||||
|
||||
mongoose.model('Application', ApplicationSchema);
|
||||
@@ -0,0 +1,34 @@
|
||||
var mongoose = require('mongoose');
|
||||
var User = mongoose.model('User');
|
||||
var slug = require('slug');
|
||||
|
||||
var CanopySchema = new mongoose.Schema({
|
||||
slug: { type: String, lowercase: true, unique: true },
|
||||
voile: String,
|
||||
taille: Number,
|
||||
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
|
||||
}, {timestamps: true, toJSON: {virtuals: true}});
|
||||
|
||||
CanopySchema.pre('validate', function (next) {
|
||||
if (!this.slug) {
|
||||
this.slugify();
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
CanopySchema.methods.slugify = function () {
|
||||
this.slug = slug(`${this.voile} ${this.taille}`) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36);
|
||||
};
|
||||
|
||||
CanopySchema.methods.toJSONFor = function(user){
|
||||
return {
|
||||
slug: this.slug,
|
||||
voile: this.voile,
|
||||
taille: this.taille,
|
||||
createdAt: this.createdAt,
|
||||
updatedAt: this.updatedAt,
|
||||
author: this.author.toProfileJSONFor(user)
|
||||
};
|
||||
};
|
||||
|
||||
mongoose.model('Canopy', CanopySchema);
|
||||
@@ -0,0 +1,20 @@
|
||||
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');
|
||||
@@ -0,0 +1,34 @@
|
||||
var mongoose = require('mongoose');
|
||||
var User = mongoose.model('User');
|
||||
var slug = require('slug');
|
||||
|
||||
var DropzoneSchema = new mongoose.Schema({
|
||||
slug: { type: String, lowercase: true, unique: true },
|
||||
lieu: String,
|
||||
oaci: String,
|
||||
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
|
||||
}, {timestamps: true, toJSON: {virtuals: true}});
|
||||
|
||||
DropzoneSchema.pre('validate', function (next) {
|
||||
if (!this.slug) {
|
||||
this.slugify();
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
DropzoneSchema.methods.slugify = function () {
|
||||
this.slug = slug(`${this.lieu} ${this.oaci}`) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36);
|
||||
};
|
||||
|
||||
DropzoneSchema.methods.toJSONFor = function(user){
|
||||
return {
|
||||
slug: this.slug,
|
||||
lieu: this.lieu,
|
||||
oaci: this.oaci,
|
||||
createdAt: this.createdAt,
|
||||
updatedAt: this.updatedAt,
|
||||
author: this.author.toProfileJSONFor(user)
|
||||
};
|
||||
};
|
||||
|
||||
mongoose.model('Dropzone', DropzoneSchema);
|
||||
@@ -0,0 +1,69 @@
|
||||
var mongoose = require('mongoose');
|
||||
var User = mongoose.model('User');
|
||||
var uniqueValidator = require('mongoose-unique-validator');
|
||||
var slug = require('slug');
|
||||
|
||||
var JumpSchema = new mongoose.Schema({
|
||||
slug: { type: String, lowercase: true, unique: true },
|
||||
date: { type: Date, default: Date.now },
|
||||
numero: { type: Number, unique: true },
|
||||
lieu: String,
|
||||
oaci: String,
|
||||
aeronef: String,
|
||||
imat: String,
|
||||
hauteur: Number,
|
||||
voile: String,
|
||||
taille: Number,
|
||||
categorie: String,
|
||||
module: String,
|
||||
participants: Number,
|
||||
sautants: [String],
|
||||
programme: String,
|
||||
accessoires: String,
|
||||
zone: String,
|
||||
dossier: String,
|
||||
video: String,
|
||||
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
|
||||
}, {timestamps: true, toJSON: {virtuals: true}});
|
||||
|
||||
JumpSchema.plugin(uniqueValidator, { message: 'is already taken' });
|
||||
|
||||
JumpSchema.pre('validate', function (next) {
|
||||
if (!this.slug) {
|
||||
this.slugify();
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
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){
|
||||
return {
|
||||
slug: this.slug,
|
||||
date: this.date,
|
||||
numero: this.numero,
|
||||
lieu: this.lieu,
|
||||
oaci: this.oaci,
|
||||
aeronef: this.aeronef,
|
||||
imat: this.imat,
|
||||
hauteur: this.hauteur,
|
||||
voile: this.voile,
|
||||
taille: this.taille,
|
||||
categorie: this.categorie,
|
||||
module: this.module,
|
||||
participants: this.participants,
|
||||
sautants: this.sautants,
|
||||
programme: this.programme,
|
||||
accessoires: this.accessoires,
|
||||
zone: this.zone,
|
||||
dossier: this.dossier,
|
||||
video: this.video,
|
||||
createdAt: this.createdAt,
|
||||
updatedAt: this.updatedAt,
|
||||
author: this.author.toProfileJSONFor(user)
|
||||
};
|
||||
};
|
||||
|
||||
mongoose.model('Jump', JumpSchema);
|
||||
@@ -0,0 +1,24 @@
|
||||
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);
|
||||
@@ -0,0 +1,87 @@
|
||||
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);
|
||||
@@ -0,0 +1,58 @@
|
||||
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);
|
||||
@@ -0,0 +1,128 @@
|
||||
var mongoose = require('mongoose');
|
||||
var uniqueValidator = require('mongoose-unique-validator');
|
||||
var crypto = require('crypto');
|
||||
var jwt = require('jsonwebtoken');
|
||||
var secret = require('../../config').secret;
|
||||
|
||||
var UserSchema = new mongoose.Schema({
|
||||
email: { type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/\S+@\S+\.\S+/, 'is invalid'], index: true },
|
||||
username: { type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/^[a-zA-Z0-9_]+$/, 'is invalid'], index: true },
|
||||
role: String,
|
||||
firstname: { type: String, required: [true, "can't be blank"] },
|
||||
lastname: { type: String, required: [true, "can't be blank"] },
|
||||
phone: { type: String, required: [true, "can't be blank"] },
|
||||
licence: Number,
|
||||
image: String,
|
||||
bg_image: String,
|
||||
favorites: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Product' }],
|
||||
following: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
|
||||
hash: String,
|
||||
salt: String
|
||||
}, { timestamps: true, toJSON: { virtuals: true } });
|
||||
|
||||
UserSchema.plugin(uniqueValidator, { message: 'is already taken.' });
|
||||
|
||||
UserSchema.methods.validPassword = function (password) {
|
||||
var hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512').toString('hex');
|
||||
return this.hash === hash;
|
||||
};
|
||||
|
||||
UserSchema.methods.setPassword = function (password) {
|
||||
this.salt = crypto.randomBytes(16).toString('hex');
|
||||
this.hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512').toString('hex');
|
||||
};
|
||||
|
||||
UserSchema.methods.generateJWT = function () {
|
||||
var today = new Date();
|
||||
var exp = new Date(today);
|
||||
exp.setDate(today.getDate() + 60);
|
||||
|
||||
return jwt.sign({
|
||||
id: this._id,
|
||||
username: this.username,
|
||||
exp: parseInt(exp.getTime() / 1000)
|
||||
}, secret, { algorithm: 'HS256' });
|
||||
};
|
||||
|
||||
UserSchema.methods.toAuthJSON = function () {
|
||||
return {
|
||||
email: this.email,
|
||||
role: this.role,
|
||||
token: this.generateJWT(),
|
||||
firstname: this.firstname,
|
||||
lastname: this.lastname,
|
||||
phone: this.phone,
|
||||
licence: this.licence,
|
||||
username: this.username,
|
||||
image: this.image || '/assets/images/users/user.jpg',
|
||||
bg_image: this.bg_image || '/assets/images/users/bg_user.jpg'
|
||||
};
|
||||
};
|
||||
|
||||
UserSchema.methods.toJSONFor = function () {
|
||||
return {
|
||||
email: this.email,
|
||||
role: this.role,
|
||||
firstname: this.firstname,
|
||||
lastname: this.lastname,
|
||||
phone: this.phone,
|
||||
licence: this.licence,
|
||||
username: this.username,
|
||||
image: this.image || '/assets/images/users/user.jpg',
|
||||
bg_image: this.bg_image || '/assets/images/users/bg_user.jpg'
|
||||
};
|
||||
};
|
||||
|
||||
UserSchema.methods.toProfileJSONFor = function (user) {
|
||||
return {
|
||||
email: this.email,
|
||||
firstname: this.firstname,
|
||||
lastname: this.lastname,
|
||||
phone: this.phone,
|
||||
licence: this.licence,
|
||||
username: this.username,
|
||||
image: this.image || '/assets/images/users/user.jpg',
|
||||
bg_image: this.bg_image || '/assets/images/users/bg_user.jpg',
|
||||
following: user ? user.isFollowing(this._id) : false
|
||||
};
|
||||
};
|
||||
|
||||
UserSchema.methods.favorite = function (id) {
|
||||
if (this.favorites.indexOf(id) === -1) {
|
||||
this.favorites.push(id);
|
||||
}
|
||||
|
||||
return this.save();
|
||||
};
|
||||
|
||||
UserSchema.methods.unfavorite = function (id) {
|
||||
this.favorites.remove(id);
|
||||
return this.save();
|
||||
};
|
||||
|
||||
UserSchema.methods.isFavorite = function (id) {
|
||||
return this.favorites.some(function (favoriteId) {
|
||||
return favoriteId.toString() === id.toString();
|
||||
});
|
||||
};
|
||||
|
||||
UserSchema.methods.follow = function (id) {
|
||||
if (this.following.indexOf(id) === -1) {
|
||||
this.following.push(id);
|
||||
}
|
||||
|
||||
return this.save();
|
||||
};
|
||||
|
||||
UserSchema.methods.unfollow = function (id) {
|
||||
this.following.remove(id);
|
||||
return this.save();
|
||||
};
|
||||
|
||||
UserSchema.methods.isFollowing = function (id) {
|
||||
return this.following.some(function (followId) {
|
||||
return followId.toString() === id.toString();
|
||||
});
|
||||
};
|
||||
|
||||
mongoose.model('User', UserSchema);
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"env" : {
|
||||
"APP_ENV": "local",
|
||||
"NODE_ENV" : "development",
|
||||
"DEBUG": false,
|
||||
"MONGODB_URI": "mongodb://localhost:27017/headupdb",
|
||||
"SERVER_PORT": "3200",
|
||||
"SECRET": "$2b$10$aEsAUG7Dy8dcTORi1vaQle",
|
||||
"SENDGRID_API_KEY": "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",
|
||||
"SENDGRID_FROM_MAIL": "contact@rampeur.fr",
|
||||
"SENDGRID_TO_MAIL": "rampeur@gmail.com",
|
||||
"AUTHORIZATION_PREFIX": "Api-Key",
|
||||
"GOLDAPI_URL": "https://www.goldapi.io/api",
|
||||
"GOLDAPI_TOKEN": "goldapi-akasnfrlfiqv0xw-io",
|
||||
"COUCHDB_URL": "http://couchdb.unespace.com",
|
||||
"COUCHDB_DATABASE": "headupdb",
|
||||
"COUCHDB_DESIGN": "headup_app",
|
||||
"COUCHDB_CREDENTIAL": "cmFtcGV1cjpES3hwMjRQUw=="
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"name": "hu-api",
|
||||
"version": "1.0.0",
|
||||
"description": "Head Up API",
|
||||
"main": "app.js",
|
||||
"author": "Solide Apps <contact@rampeur.fr>",
|
||||
"contributors": [
|
||||
"Julien Gautier <rampeur@gmail.com>"
|
||||
],
|
||||
"scripts": {
|
||||
"mongo:start": "docker run --name hu-mongo -p 27017:27017 mongo & sleep 5",
|
||||
"start": "APP_ENV=production node ./app.js",
|
||||
"dev": "APP_ENV=development node ./app.js",
|
||||
"local": "APP_ENV=local nodemon ./app.js",
|
||||
"test": "newman run ./tests/api-tests.postman.json -e ./tests/env-api-tests.postman.json",
|
||||
"stop": "lsof -ti :3200 | xargs kill",
|
||||
"mongo:stop": "docker stop hu-mongo && docker rm hu-mongo"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^16.20.1 || ^18.16.1 || ^20.3.1"
|
||||
},
|
||||
"license": "UNLICENSED",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@sendgrid/mail": "^7.7.0",
|
||||
"bcrypt": "^5.1.0",
|
||||
"body-parser": "^1.20.2",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.3.1",
|
||||
"ejs": "^3.1.9",
|
||||
"errorhandler": "^1.5.1",
|
||||
"express": "^4.18.2",
|
||||
"express-jwt": "^8.4.1",
|
||||
"express-session": "^1.17.3",
|
||||
"jsonwebtoken": "^9.0.0",
|
||||
"method-override": "3.0.0",
|
||||
"methods": "1.1.2",
|
||||
"mongoose": "^6.11.2",
|
||||
"mongoose-unique-validator": "^3.1.0",
|
||||
"morgan": "^1.10.0",
|
||||
"node-fetch": "^3.3.2",
|
||||
"passport": "^0.6.0",
|
||||
"passport-headerapikey": "^1.2.2",
|
||||
"passport-local": "^1.0.0",
|
||||
"request": "^2.88.2",
|
||||
"slug": "^8.2.2",
|
||||
"underscore": "^1.13.6",
|
||||
"uuid": "^9.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"newman": "^5.3.2",
|
||||
"nodemon": "^2.0.22"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
var router = require('express').Router(),
|
||||
mongoose = require('mongoose'),
|
||||
Aeronef = mongoose.model('Aeronef'),
|
||||
Jump = mongoose.model('Jump'),
|
||||
User = mongoose.model('User');
|
||||
const auth = require('../auth');
|
||||
|
||||
|
||||
router.get('/', 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 = [
|
||||
{
|
||||
'$match': {
|
||||
'$expr': {
|
||||
'$eq': [ '$author' , { '$toObjectId': user._id.toString() } ]
|
||||
}
|
||||
}
|
||||
}, {
|
||||
'$group': {
|
||||
'_id': {
|
||||
'aeronef': '$aeronef',
|
||||
'imat': '$imat'
|
||||
},
|
||||
'count': {
|
||||
'$sum': 1
|
||||
}
|
||||
}
|
||||
}
|
||||
];
|
||||
Promise.all([
|
||||
Jump.aggregate(query)
|
||||
.limit(Number(limit))
|
||||
.skip(Number(offset))
|
||||
.exec()
|
||||
//Aeronef.count(query)
|
||||
]).then(function (results) {
|
||||
var aeronefs = results[0];
|
||||
//var aeronefsCount = results[1];
|
||||
return res.json({
|
||||
aeronefs: aeronefs,
|
||||
aeronefsCount: aeronefs.length
|
||||
});
|
||||
/*
|
||||
return res.json({
|
||||
aeronefs: aeronefs.map(function (aeronef) {
|
||||
return aeronef.toJSONFor(user);
|
||||
}),
|
||||
aeronefsCount: aeronefsCount
|
||||
});
|
||||
*/
|
||||
}).catch(next);
|
||||
}).catch(next);
|
||||
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,160 @@
|
||||
var router = require('express').Router(),
|
||||
mongoose = require('mongoose'),
|
||||
Application = mongoose.model('Application'),
|
||||
User = mongoose.model('User');
|
||||
const auth = require('../auth'),
|
||||
mailer = require('@sendgrid/mail');
|
||||
|
||||
mailer.setApiKey(process.env.SENDGRID_API_KEY);
|
||||
|
||||
// Preload application objects on routes with ':application'
|
||||
router.param('application', function (req, res, next, slug) {
|
||||
Application.findOne({ slug: slug })
|
||||
.populate('author')
|
||||
.then(function (application) {
|
||||
if (!application) {
|
||||
return res.sendStatus(404);
|
||||
}
|
||||
req.application = application;
|
||||
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.apikey !== 'undefined') {
|
||||
query.apikey = req.query.apikey;
|
||||
}
|
||||
if (typeof req.query.maskedkey !== 'undefined') {
|
||||
query.maskedkey = req.query.maskedkey;
|
||||
}
|
||||
|
||||
Promise.all([
|
||||
req.query.author ? User.findOne({ username: req.query.author }) : null
|
||||
]).then(function (author) {
|
||||
if (author[0]) {
|
||||
query.author = author[0]._id;
|
||||
}
|
||||
return Promise.all([
|
||||
Application.find(query)
|
||||
.limit(Number(limit))
|
||||
.skip(Number(offset))
|
||||
.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];
|
||||
|
||||
return res.json({
|
||||
applications: applications.map(function (application) {
|
||||
return application.toJSONFor(user);
|
||||
}),
|
||||
applicationsCount: applicationsCount
|
||||
});
|
||||
});
|
||||
}).catch(next);
|
||||
});
|
||||
|
||||
router.post('/', auth.required, function (req, res, next) {
|
||||
Promise.all([
|
||||
User.findById(req.payload.id),
|
||||
auth.generateAPIKey()
|
||||
]).then(function (results) {
|
||||
var user = results[0];
|
||||
var 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);
|
||||
application.author = user;
|
||||
application.apikey = keys.encrypted;
|
||||
application.maskedkey = keys.masked;
|
||||
return application.save().then(function () {
|
||||
var msg = {
|
||||
to: user.email,
|
||||
from: process.env.SENDGRID_FROM_MAIL,
|
||||
subject: `Api-Key ${application.title}`,
|
||||
text: `Votre Api-Key: ${keys.key}\nAttention, cette Api-Key doit être conservée et ne sera plus affichée.\n\n${application.title}\n${application.description}`,
|
||||
html: `<h2>${application.title}</h2>
|
||||
<p>
|
||||
Votre Api-Key: ${keys.key}<br />
|
||||
<strong>Attention, cette Api-Key doit être conservée et ne sera plus affichée.</strong>
|
||||
</p>
|
||||
<hr />
|
||||
<p>${application.description}</p>`
|
||||
};
|
||||
mailer.send(msg).then(resp => {
|
||||
return res.json({ application: application.toJSONFor(user) });
|
||||
})
|
||||
.catch(err => {
|
||||
res.sendStatus(500).json({message: "A SendGrid error occured while sending an email", err: err});
|
||||
});
|
||||
});
|
||||
}).catch(next);
|
||||
});
|
||||
|
||||
// return an application
|
||||
router.get('/:application', auth.required, function (req, res, next) {
|
||||
Promise.all([
|
||||
req.payload ? User.findById(req.payload.id) : null,
|
||||
req.application.populate('author')
|
||||
]).then(function (results) {
|
||||
var user = results[0];
|
||||
return res.json({ application: req.application.toJSONFor(user) });
|
||||
}).catch(next);
|
||||
});
|
||||
|
||||
router.put('/:application', auth.required, function (req, res, next) {
|
||||
User.findById(req.payload.id).then(function (user) {
|
||||
if (req.application.author._id.toString() === req.payload.id.toString()) {
|
||||
if (typeof req.body.application.title !== 'undefined') {
|
||||
req.application.title = req.body.application.title;
|
||||
}
|
||||
if (typeof req.body.application.description !== 'undefined') {
|
||||
req.application.description = req.body.application.description;
|
||||
}
|
||||
if (typeof req.body.application.apikey !== 'undefined') {
|
||||
req.application.apikey = req.body.application.apikey;
|
||||
}
|
||||
if (typeof req.body.application.maskedkey !== 'undefined') {
|
||||
req.application.maskedkey = req.body.application.maskedkey;
|
||||
}
|
||||
req.application.save().then(function (application) {
|
||||
return res.json({ application: application.toJSONFor(user) });
|
||||
}).catch(next);
|
||||
} else {
|
||||
return res.sendStatus(403);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// delete application
|
||||
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."});
|
||||
}
|
||||
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."});
|
||||
}
|
||||
}).catch(next);
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,129 @@
|
||||
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;
|
||||
@@ -0,0 +1,58 @@
|
||||
var router = require('express').Router(),
|
||||
mongoose = require('mongoose'),
|
||||
Canopy = mongoose.model('Canopy'),
|
||||
Jump = mongoose.model('Jump'),
|
||||
User = mongoose.model('User');
|
||||
const auth = require('../auth');
|
||||
|
||||
|
||||
router.get('/', 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 = [
|
||||
{
|
||||
'$match': {
|
||||
'$expr': {
|
||||
'$eq': [ '$author' , { '$toObjectId': user._id.toString() } ]
|
||||
}
|
||||
}
|
||||
}, {
|
||||
'$group': {
|
||||
'_id': {
|
||||
'voile': '$voile',
|
||||
'taille': '$taille'
|
||||
},
|
||||
'count': {
|
||||
'$sum': 1
|
||||
}
|
||||
}
|
||||
}
|
||||
];
|
||||
Promise.all([
|
||||
Jump.aggregate(query)
|
||||
.limit(Number(limit))
|
||||
.skip(Number(offset))
|
||||
.exec()
|
||||
]).then(function (results) {
|
||||
var canopies = results[0];
|
||||
return res.json({
|
||||
canopies: canopies,
|
||||
canopiesCount: canopies.length
|
||||
});
|
||||
}).catch(next);
|
||||
}).catch(next);
|
||||
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,58 @@
|
||||
var router = require('express').Router(),
|
||||
mongoose = require('mongoose'),
|
||||
Dropzone = mongoose.model('Dropzone'),
|
||||
Jump = mongoose.model('Jump'),
|
||||
User = mongoose.model('User');
|
||||
const auth = require('../auth');
|
||||
|
||||
|
||||
router.get('/', 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 = [
|
||||
{
|
||||
'$match': {
|
||||
'$expr': {
|
||||
'$eq': [ '$author' , { '$toObjectId': user._id.toString() } ]
|
||||
}
|
||||
}
|
||||
}, {
|
||||
'$group': {
|
||||
'_id': {
|
||||
'lieu': '$lieu',
|
||||
'oaci': '$oaci'
|
||||
},
|
||||
'count': {
|
||||
'$sum': 1
|
||||
}
|
||||
}
|
||||
}
|
||||
];
|
||||
Promise.all([
|
||||
Jump.aggregate(query)
|
||||
.limit(Number(limit))
|
||||
.skip(Number(offset))
|
||||
.exec()
|
||||
]).then(function (results) {
|
||||
var dropzones = results[0];
|
||||
return res.json({
|
||||
dropzones: dropzones,
|
||||
dropzonesCount: dropzones.length
|
||||
});
|
||||
}).catch(next);
|
||||
}).catch(next);
|
||||
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,28 @@
|
||||
var router = require('express').Router();
|
||||
|
||||
router.use('/', require('./users'));
|
||||
router.use('/profiles', require('./profiles'));
|
||||
router.use('/applications', require('./applications'));
|
||||
router.use('/aeronefs', require('./aeronefs'));
|
||||
router.use('/canopies', require('./canopies'));
|
||||
router.use('/dropzones', require('./dropzones'));
|
||||
router.use('/jumps', require('./jumps'));
|
||||
/*
|
||||
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({
|
||||
errors: Object.keys(err.errors).reduce(function (errors, key) {
|
||||
errors[key] = err.errors[key].message;
|
||||
return errors;
|
||||
}, {})
|
||||
});
|
||||
}
|
||||
return next(err);
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,236 @@
|
||||
var router = require('express').Router(),
|
||||
mongoose = require('mongoose'),
|
||||
Jump = mongoose.model('Jump'),
|
||||
User = mongoose.model('User');
|
||||
const auth = require('../auth');
|
||||
|
||||
// Preload jump objects on routes with ':jump'
|
||||
router.param('jump', function (req, res, next, slug) {
|
||||
Jump.findOne({ slug: slug })
|
||||
.populate('author')
|
||||
.then(function (jump) {
|
||||
if (!jump) {
|
||||
return res.sendStatus(404);
|
||||
}
|
||||
req.jump = jump;
|
||||
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];
|
||||
|
||||
if (author) {
|
||||
query.author = author._id;
|
||||
}
|
||||
|
||||
return Promise.all([
|
||||
Jump.find(query)
|
||||
.limit(Number(limit))
|
||||
.skip(Number(offset))
|
||||
.sort({ numero: 'asc' })
|
||||
.populate('author')
|
||||
.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];
|
||||
|
||||
return res.json({
|
||||
jumps: jumps.map(function (jump) {
|
||||
return jump.toJSONFor(user);
|
||||
}),
|
||||
jumpsCount: jumpsCount
|
||||
});
|
||||
});
|
||||
}).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([
|
||||
Jump.find(query)
|
||||
.limit(Number(limit))
|
||||
.skip(Number(offset))
|
||||
.populate('author')
|
||||
.exec(),
|
||||
Jump.count(query)
|
||||
]).then(function (results) {
|
||||
var jumps = results[0];
|
||||
var jumpsCount = results[1];
|
||||
return res.json({
|
||||
jumps: jumps.map(function (jump) {
|
||||
return jump.toJSONFor(user);
|
||||
}),
|
||||
jumpsCount: jumpsCount
|
||||
});
|
||||
}).catch(next);
|
||||
});
|
||||
});
|
||||
|
||||
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);
|
||||
if (!user) {
|
||||
return res.sendStatus(401);
|
||||
}
|
||||
var jump = new Jump(req.body.jump);
|
||||
jump.author = user;
|
||||
//jump.numero = numero;
|
||||
return jump.save().then(function () {
|
||||
return res.json({ jump: jump.toJSONFor(user) });
|
||||
});
|
||||
}).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];
|
||||
if (!user) {
|
||||
return res.sendStatus(401);
|
||||
}
|
||||
if (req.jump.author._id.toString() !== req.payload.id.toString()) {
|
||||
return res.sendStatus(403);
|
||||
}
|
||||
return res.json({ jump: req.jump.toJSONFor(user) });
|
||||
}).catch(next);
|
||||
});
|
||||
|
||||
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];
|
||||
if (!user) {
|
||||
return res.sendStatus(401);
|
||||
}
|
||||
if (req.jump.author._id.toString() !== req.payload.id.toString()) {
|
||||
return res.sendStatus(403);
|
||||
}
|
||||
if (typeof req.body.jump.date !== 'undefined') {
|
||||
req.jump.date = req.body.jump.date;
|
||||
}
|
||||
if (typeof req.body.jump.numero !== 'undefined') {
|
||||
req.jump.numero = req.body.jump.numero;
|
||||
}
|
||||
if (typeof req.body.jump.lieu !== 'undefined') {
|
||||
req.jump.lieu = req.body.jump.lieu;
|
||||
}
|
||||
if (typeof req.body.jump.oaci !== 'undefined') {
|
||||
req.jump.oaci = req.body.jump.oaci;
|
||||
}
|
||||
if (typeof req.body.jump.aeronef !== 'undefined') {
|
||||
req.jump.aeronef = req.body.jump.aeronef;
|
||||
}
|
||||
if (typeof req.body.jump.imat !== 'undefined') {
|
||||
req.jump.imat = req.body.jump.imat;
|
||||
}
|
||||
if (typeof req.body.jump.hauteur !== 'undefined') {
|
||||
req.jump.hauteur = req.body.jump.hauteur;
|
||||
}
|
||||
if (typeof req.body.jump.voile !== 'undefined') {
|
||||
req.jump.voile = req.body.jump.voile;
|
||||
}
|
||||
if (typeof req.body.jump.taille !== 'undefined') {
|
||||
req.jump.taille = req.body.jump.taille;
|
||||
}
|
||||
if (typeof req.body.jump.categorie !== 'undefined') {
|
||||
req.jump.categorie = req.body.jump.categorie;
|
||||
}
|
||||
if (typeof req.body.jump.module !== 'undefined') {
|
||||
req.jump.module = req.body.jump.module;
|
||||
}
|
||||
if (typeof req.body.jump.participants !== 'undefined') {
|
||||
req.jump.participants = req.body.jump.participants;
|
||||
}
|
||||
if (typeof req.body.jump.sautants !== 'undefined') {
|
||||
req.jump.sautants = req.body.jump.sautants;
|
||||
}
|
||||
if (typeof req.body.jump.programme !== 'undefined') {
|
||||
req.jump.programme = req.body.jump.programme;
|
||||
}
|
||||
if (typeof req.body.jump.accessoires !== 'undefined') {
|
||||
req.jump.accessoires = req.body.jump.accessoires;
|
||||
}
|
||||
if (typeof req.body.jump.zone !== 'undefined') {
|
||||
req.jump.zone = req.body.jump.zone;
|
||||
}
|
||||
if (typeof req.body.jump.dossier !== 'undefined') {
|
||||
req.jump.dossier = req.body.jump.dossier;
|
||||
}
|
||||
if (typeof req.body.jump.video !== 'undefined') {
|
||||
req.jump.video = req.body.jump.video;
|
||||
}
|
||||
|
||||
return req.jump.save().then(function (jump) {
|
||||
return res.json({ jump: jump.toJSONFor(user) });
|
||||
});
|
||||
}).catch(next);
|
||||
});
|
||||
|
||||
// delete jump
|
||||
router.delete('/:jump', auth.required, function (req, res, next) {
|
||||
User.findById(req.payload.id).then(function (user) {
|
||||
if (!user) {
|
||||
return res.sendStatus(401);
|
||||
}
|
||||
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);
|
||||
}
|
||||
}).catch(next);
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,64 @@
|
||||
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;
|
||||
@@ -0,0 +1,133 @@
|
||||
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;
|
||||
@@ -0,0 +1,238 @@
|
||||
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;
|
||||
@@ -0,0 +1,57 @@
|
||||
var router = require('express').Router(),
|
||||
mongoose = require('mongoose'),
|
||||
User = mongoose.model('User');
|
||||
const auth = require('../auth');
|
||||
|
||||
// Preload user profile on routes with ':username'
|
||||
router.param('username', function (req, res, next, username) {
|
||||
User.findOne({ username: username }).then(function (user) {
|
||||
if (!user) {
|
||||
return res.sendStatus(404);
|
||||
}
|
||||
req.profile = user;
|
||||
|
||||
return next();
|
||||
}).catch(next);
|
||||
});
|
||||
|
||||
router.get('/:username', auth.optional, function (req, res, next) {
|
||||
if (req.payload) {
|
||||
User.findById(req.payload.id).then(function (user) {
|
||||
if (!user) {
|
||||
return res.json({ profile: req.profile.toProfileJSONFor(false) });
|
||||
}
|
||||
return res.json({ profile: req.profile.toProfileJSONFor(user) });
|
||||
});
|
||||
} else {
|
||||
return res.json({ profile: req.profile.toProfileJSONFor(false) });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/:username/follow', auth.required, function (req, res, next) {
|
||||
var profileId = req.profile._id;
|
||||
|
||||
User.findById(req.payload.id).then(function (user) {
|
||||
if (!user) {
|
||||
return res.sendStatus(401);
|
||||
}
|
||||
return user.follow(profileId).then(function () {
|
||||
return res.json({ profile: req.profile.toProfileJSONFor(user) });
|
||||
});
|
||||
}).catch(next);
|
||||
});
|
||||
|
||||
router.delete('/:username/follow', auth.required, function (req, res, next) {
|
||||
var profileId = req.profile._id;
|
||||
|
||||
User.findById(req.payload.id).then(function (user) {
|
||||
if (!user) {
|
||||
return res.sendStatus(401);
|
||||
}
|
||||
return user.unfollow(profileId).then(function () {
|
||||
return res.json({ profile: req.profile.toProfileJSONFor(user) });
|
||||
});
|
||||
}).catch(next);
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,117 @@
|
||||
var router = require('express').Router(),
|
||||
mongoose = require('mongoose'),
|
||||
User = mongoose.model('User');
|
||||
const passport = require('passport'),
|
||||
auth = require('../auth');
|
||||
|
||||
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.json({ user: user.toAuthJSON() });
|
||||
}).catch(next);
|
||||
});
|
||||
|
||||
router.put('/user', auth.required, function (req, res, next) {
|
||||
User.findById(req.payload.id).then(function (user) {
|
||||
if (!user) {
|
||||
return res.sendStatus(401);
|
||||
}
|
||||
if (typeof req.body.user.username !== 'undefined') {
|
||||
user.username = req.body.user.username;
|
||||
}
|
||||
if (typeof req.body.user.email !== 'undefined') {
|
||||
user.email = req.body.user.email;
|
||||
}
|
||||
if (typeof req.body.user.firstname !== 'undefined') {
|
||||
user.firstname = req.body.user.firstname;
|
||||
}
|
||||
if (typeof req.body.user.lastname !== 'undefined') {
|
||||
user.lastname = req.body.user.lastname;
|
||||
}
|
||||
if (typeof req.body.user.phone !== 'undefined') {
|
||||
user.phone = req.body.user.phone;
|
||||
}
|
||||
if (typeof req.body.user.licence !== 'undefined') {
|
||||
user.licence = req.body.user.licence;
|
||||
}
|
||||
if (typeof req.body.user.image !== 'undefined') {
|
||||
user.image = req.body.user.image;
|
||||
}
|
||||
if (typeof req.body.user.bg_image !== 'undefined') {
|
||||
user.bg_image = req.body.user.bg_image;
|
||||
}
|
||||
if (typeof req.body.user.password !== 'undefined') {
|
||||
user.setPassword(req.body.user.password);
|
||||
}
|
||||
if (typeof req.body.user.role !== 'undefined') {
|
||||
user.role = req.body.user.role;
|
||||
}
|
||||
|
||||
return user.save().then(function () {
|
||||
return res.json({ user: user.toAuthJSON() });
|
||||
});
|
||||
}).catch(next);
|
||||
});
|
||||
|
||||
router.post('/users/login', function (req, res, next) {
|
||||
if (!req.body.user.email) {
|
||||
return res.status(422).json({ errors: { email: "can't be blank" } });
|
||||
}
|
||||
if (!req.body.user.password) {
|
||||
return res.status(422).json({ errors: { password: "can't be blank" } });
|
||||
}
|
||||
passport.authenticate('local', { session: false }, function (err, user, info) {
|
||||
if (err) {
|
||||
return next(err);
|
||||
}
|
||||
if (user) {
|
||||
user.token = user.generateJWT();
|
||||
return res.json({ user: user.toAuthJSON() });
|
||||
} else {
|
||||
return res.status(422).json(info);
|
||||
}
|
||||
})(req, res, next);
|
||||
});
|
||||
|
||||
router.get('/authenticate', function (req, res, next) {
|
||||
passport.authenticate('headerapikey', { session: false }, function (err, application, info) {
|
||||
if (err) {
|
||||
return res.status(err.status || 500).json({message: "An authentication error occured.", err: err.message});
|
||||
//return next(err);
|
||||
}
|
||||
if (!application) {
|
||||
return res.status(401).json({message: "Unauthorized - You are not allowed to access this resource.", err: err, info: info});
|
||||
}
|
||||
if (application.author) {
|
||||
application.author.token = application.author.generateJWT();
|
||||
return res.json({ user: application.author.toAuthJSON(), application: application.toAuthJSON() });
|
||||
} else {
|
||||
return res.status(422).json(info);
|
||||
}
|
||||
})(req, res, next);
|
||||
});
|
||||
router.post('/users', function (req, res, next) {
|
||||
var user = new User();
|
||||
if (typeof req.body.user.username !== 'undefined') {
|
||||
user.username = req.body.user.username;
|
||||
} else {
|
||||
user.username = `${req.body.user.firstname}_${req.body.user.lastname}`;
|
||||
}
|
||||
user.email = req.body.user.email;
|
||||
user.firstname = req.body.user.firstname;
|
||||
user.lastname = req.body.user.lastname;
|
||||
user.phone = req.body.user.phone;
|
||||
if (typeof req.body.user.licence !== 'undefined') {
|
||||
user.licence = req.body.user.licence;
|
||||
}
|
||||
user.setPassword(req.body.user.password);
|
||||
user.role = 'User'; // valeurs possibles : 'User' or 'Admin'
|
||||
|
||||
user.save().then(function () {
|
||||
return res.json({ user: user.toAuthJSON() });
|
||||
}).catch(next);
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,83 @@
|
||||
|
||||
//var jwt = require('express-jwt');
|
||||
var { expressjwt: jwt } = require("express-jwt"),
|
||||
secret = require('../config').secret,
|
||||
bcrypt = require('bcrypt');
|
||||
const { v4 } = require('uuid'),
|
||||
passport = require('passport'),
|
||||
auths = ['Api-Key', 'Basic', 'Bearer', 'Token'];
|
||||
|
||||
function getTokenFromHeader(req) {
|
||||
if(req.headers.authorization && auths.indexOf(req.headers.authorization.split(' ')[0]) !== -1) {
|
||||
return req.headers.authorization.split(' ')[1];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const auth = {
|
||||
requiredJwt: jwt({
|
||||
secret: secret,
|
||||
algorithms: ['HS256'],
|
||||
requestProperty: 'payload',
|
||||
getToken: getTokenFromHeader
|
||||
}),
|
||||
optional: jwt({
|
||||
secret: secret,
|
||||
algorithms: ['HS256'],
|
||||
requestProperty: 'payload',
|
||||
credentialsRequired: false,
|
||||
getToken: getTokenFromHeader
|
||||
}),
|
||||
required: async (req, res, next) => {
|
||||
if(req.headers.authorization && req.headers.authorization.split(' ')[0] === process.env.AUTHORIZATION_PREFIX) {
|
||||
passport.authenticate('headerapikey', { session: false }, function (err, application, info) {
|
||||
if (err) {
|
||||
//return res.json({message: "An authentication error occured (required).", err: err.message});
|
||||
//return res.status(err.status || 500).json({message: "An authentication error occured (required).", err: err.message});
|
||||
return next({message: "An authentication error occured.", err: err.message});
|
||||
}
|
||||
if (!application) {
|
||||
return res.status(401).json({message: "Unauthorized - You are not allowed to access this resource.", err: err, info: info});
|
||||
}
|
||||
req.application = application;
|
||||
return next();
|
||||
})(req, res, next);
|
||||
} else {
|
||||
return jwt({
|
||||
secret: secret,
|
||||
algorithms: ['HS256'],
|
||||
requestProperty: 'payload',
|
||||
getToken: getTokenFromHeader
|
||||
})(req, res, next);
|
||||
}
|
||||
},
|
||||
getAuthType: (req) => {
|
||||
if(req.headers.authorization && auths.indexOf(req.headers.authorization.split(' ')[0]) !== -1) {
|
||||
let value = req.headers.authorization.split(' ')[0];
|
||||
return value;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
generateAPIKey: async () => {
|
||||
const key = v4().replace(/-/g, '');
|
||||
const salt = secret;
|
||||
// Génération d'un salt aléatoire : const salt = await Promise.resolve(bcrypt.genSalt(10));
|
||||
const maskedKey = `${key.slice(0, 4)}...${key.slice(-4)}`;
|
||||
const encryptedKey = await Promise.resolve(bcrypt.hash(key, salt));
|
||||
return { key: key, masked: maskedKey, encrypted: encryptedKey};
|
||||
},
|
||||
authenticateKey: async (req, res, next) => {
|
||||
passport.authenticate('headerapikey', { session: false }, function (err, application, info) {
|
||||
if (err) {
|
||||
return res.status(err.status || 500).json({message: "An authentication error occured (authenticateKey).", err: err.message});
|
||||
}
|
||||
if (!application) {
|
||||
return res.status(401).json({message: "Unauthorized - You are not allowed to access this resource.", err: err, info: info});
|
||||
}
|
||||
req.application = application;
|
||||
return next();
|
||||
})(req, res, next);
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = auth;
|
||||
@@ -0,0 +1,4 @@
|
||||
var router = require('express').Router();
|
||||
router.use('/api', require('./api'));
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,68 @@
|
||||
const chalk = require('chalk');
|
||||
const nodeFetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
|
||||
|
||||
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) => {
|
||||
let today = new Date();
|
||||
let dateString = `${today.toLocaleDateString()} ${today.toLocaleTimeString()}`;
|
||||
if (delimiter) {
|
||||
dateString = `[${dateString}]`;
|
||||
}
|
||||
|
||||
return dateString;
|
||||
},
|
||||
getDateTimeISOString: (delimiter = true) => {
|
||||
let today = new Date();
|
||||
let dateString = today.toISOString();
|
||||
if (delimiter) {
|
||||
dateString = `[${dateString}]`;
|
||||
}
|
||||
|
||||
return dateString;
|
||||
},
|
||||
async fetchApi(price, next) {
|
||||
let url = `${process.env.GOLDAPI_URL}/${price.metal}/${price.currency}`;
|
||||
// url pour provoquer une erreur en dev : url = `https://www.goldapi.ioppppp/api/${price.metal}/${price.currency}`;
|
||||
let options = {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'x-access-token': process.env.GOLDAPI_TOKEN,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
redirect: 'follow'
|
||||
};
|
||||
try {
|
||||
// Pour tester le retour d'erreur : return { errors: { name: 'error name', message: 'error message', type: 'TYPE', code: 'CODE' } };
|
||||
const response = await nodeFetch(url, options);
|
||||
if (response.status >= 200 && response.status < 400) {
|
||||
console.log(`${utils.getDateTimeISOString()}`, chalk.green(`${price.metal} | ${price.currency} - Réception du prix spot via API`), chalk.magenta(price.price), `${response.status} ${response.statusText}`);
|
||||
price = response.json();
|
||||
price.then(values => {
|
||||
values.timestamp *= 1000;
|
||||
return values;
|
||||
});
|
||||
} else {
|
||||
console.log(`${utils.getDateTimeISOString()}`, chalk.red(`${price.metal} | ${price.currency} - Erreur ${response.status} ${response.statusText} - Réutilisation du prix stocké`), chalk.magenta(price.price));
|
||||
price = { errors: { name: response.statusText, message: `Une erreur ${response.status} '${response.statusText}' est survenue lors de la récupération des prix spots`, type: 'API Error', code: response.status } };
|
||||
}
|
||||
return price;
|
||||
} catch (error) {
|
||||
console.log(`${utils.getDateTimeISOString()}`, chalk.red(`${price.metal} | ${price.currency} - fetchApi error`));
|
||||
return { errors: { name: error.name, message: error.message, type: error.type, code: error.code } };
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = utils;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"id": "4aa60b52-97fc-456d-4d4f-14a350e95dff",
|
||||
"name": "Head Up API Tests - Environment",
|
||||
"values": [
|
||||
{
|
||||
"enabled": true,
|
||||
"key": "apiUrl",
|
||||
"value": "http://localhost:3200/api",
|
||||
"type": "text"
|
||||
}
|
||||
],
|
||||
"timestamp": 1505871382668,
|
||||
"_postman_variable_scope": "environment",
|
||||
"_postman_exported_at": "2017-09-20T01:36:34.835Z",
|
||||
"_postman_exported_using": "Postman/5.2.0"
|
||||
}
|
||||
Reference in New Issue
Block a user