spee.ch/routes/serve-routes.js

82 lines
2.4 KiB
JavaScript
Raw Normal View History

const errorHandlers = require('../helpers/libraries/errorHandlers.js');
const serveController = require('../controllers/serveController.js');
const logger = require('winston');
2017-06-30 07:26:29 +02:00
const { postToStats, sendGoogleAnalytics } = require('../controllers/statsController.js');
2017-06-30 01:10:06 +02:00
2017-06-20 00:25:14 +02:00
function serveFile ({ fileName, fileType, filePath }, res) {
2017-06-20 05:22:23 +02:00
logger.info(`serving file ${fileName}`);
// set default options
const options = {
headers: {
'X-Content-Type-Options': 'nosniff',
2017-06-20 00:25:14 +02:00
'Content-Type' : fileType,
},
};
// adjust default options as needed
// eslint-disable-next-line camelcase
2017-06-20 00:25:14 +02:00
switch (fileType) {
case 'image/jpeg':
break;
case 'image/gif':
break;
case 'image/png':
break;
case 'video/mp4':
break;
default:
logger.warn('sending unknown file type as .jpeg');
options['headers']['Content-Type'] = 'image/jpeg';
break;
}
// send file
2017-06-20 00:25:14 +02:00
res.status(200).sendFile(filePath, options);
}
2017-06-30 02:10:14 +02:00
function sendAnalyticsAndLog (ip, originalUrl) {
// google analytics
sendGoogleAnalytics('serve', ip, originalUrl);
// logging
logger.verbose(`GET request on ${originalUrl} from ${ip}`);
}
module.exports = (app) => {
// route to fetch one free public claim
2017-06-30 02:10:14 +02:00
app.get('/:name/:claim_id', ({ ip, originalUrl, params }, res) => {
sendAnalyticsAndLog(ip, originalUrl);
// begin image-serve processes
serveController
2017-06-28 08:04:47 +02:00
.getClaimByClaimId(params.name, params.claim_id)
.then(fileInfo => {
// check to make sure a file was found
if (!fileInfo) {
res.status(307).render('noClaims');
return;
}
2017-06-29 23:48:27 +02:00
postToStats('serve', originalUrl, ip, 'success');
serveFile(fileInfo, res);
})
.catch(error => {
2017-06-29 23:48:27 +02:00
errorHandlers.handleRequestError('serve', originalUrl, ip, error, res);
});
});
// route to fetch one free public claim
2017-06-30 02:10:14 +02:00
app.get('/:name', ({ ip, originalUrl, params }, res) => {
sendAnalyticsAndLog(ip, originalUrl);
// begin image-serve processes
serveController
.getClaimByName(params.name)
.then(fileInfo => {
// check to make sure a file was found
if (!fileInfo) {
res.status(307).render('noClaims');
return;
}
2017-06-29 23:48:27 +02:00
postToStats('serve', originalUrl, ip, 'success');
serveFile(fileInfo, res);
})
.catch(error => {
2017-06-29 23:48:27 +02:00
errorHandlers.handleRequestError('serve', originalUrl, ip, error, res);
});
});
};