spee.ch/routes/serve-routes.js
2017-06-27 21:39:33 -07:00

66 lines
2 KiB
JavaScript

const errorHandlers = require('../helpers/libraries/errorHandlers.js');
const serveController = require('../controllers/serveController.js');
const logger = require('winston');
const { postRequestAnalytics } = require('../helpers/libraries/analytics');
function serveFile ({ fileName, fileType, filePath }, res) {
logger.info(`serving file ${fileName}`);
// set default options
const options = {
headers: {
'X-Content-Type-Options': 'nosniff',
'Content-Type' : fileType,
},
};
// adjust default options as needed
// eslint-disable-next-line camelcase
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
res.status(200).sendFile(filePath, options);
}
module.exports = (app) => {
// route to fetch one free public claim
app.get('/:name/:claim_id', ({ originalUrl, params, ip }, res) => {
logger.debug(`GET request on ${originalUrl} from ${ip}`);
// begin image-serve processes
serveController
.getClaimByClaimId(params.name, params.claim_id)
.then(fileInfo => {
postRequestAnalytics(originalUrl, ip, 'success');
serveFile(fileInfo, res);
})
.catch(error => {
postRequestAnalytics(originalUrl, ip, error);
errorHandlers.handleRequestError(error, res);
});
});
// route to fetch one free public claim
app.get('/:name', ({ originalUrl, params, ip }, res) => {
logger.debug(`GET request on ${originalUrl} from ${ip}`);
// begin image-serve processes
serveController
.getClaimByName(params.name)
.then(fileInfo => {
postRequestAnalytics(originalUrl, ip, 'success');
serveFile(fileInfo, res);
})
.catch(error => {
postRequestAnalytics(originalUrl, ip, error);
errorHandlers.handleRequestError(error, res);
});
});
};