2018-04-29 22:00:41 +02:00
|
|
|
const logger = require('winston');
|
2019-02-20 07:30:46 +01:00
|
|
|
const transformImage = require('./transformImage');
|
|
|
|
const serveFile = async ({ filePath, fileType }, res, originalUrl) => {
|
|
|
|
const queryObject = {};
|
|
|
|
// TODO: replace quick/dirty try catch with better practice
|
|
|
|
try {
|
|
|
|
originalUrl
|
|
|
|
.split('?')[1]
|
|
|
|
.split('&')
|
|
|
|
.map(pair => {
|
|
|
|
if (pair.includes('=')) {
|
|
|
|
let parr = pair.split('=');
|
|
|
|
queryObject[parr[0]] = parr[1];
|
|
|
|
} else queryObject[pair] = true;
|
|
|
|
});
|
|
|
|
} catch (e) {}
|
2018-04-29 22:00:41 +02:00
|
|
|
|
2018-07-08 00:03:21 +02:00
|
|
|
if (!fileType) {
|
|
|
|
logger.error(`no fileType provided for ${filePath}`);
|
|
|
|
}
|
2019-02-20 07:30:46 +01:00
|
|
|
|
|
|
|
let mediaType = fileType ? fileType.substr(0, fileType.indexOf('/')) : '';
|
|
|
|
const transform =
|
|
|
|
mediaType === 'image' && queryObject.hasOwnProperty('h') && queryObject.hasOwnProperty('w');
|
|
|
|
|
2018-04-29 22:00:41 +02:00
|
|
|
const sendFileOptions = {
|
|
|
|
headers: {
|
2019-02-20 07:30:46 +01:00
|
|
|
'X-Content-Type-Options': 'nosniff',
|
|
|
|
'Content-Type': fileType,
|
|
|
|
'Access-Control-Allow-Origin': '*',
|
2018-12-05 20:54:14 +01:00
|
|
|
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
|
2018-04-29 22:00:41 +02:00
|
|
|
},
|
|
|
|
};
|
2018-07-08 00:03:21 +02:00
|
|
|
logger.debug(`fileOptions for ${filePath}:`, sendFileOptions);
|
2019-02-20 07:30:46 +01:00
|
|
|
if (transform) {
|
|
|
|
logger.debug(`transforming and sending file`);
|
|
|
|
|
|
|
|
let xformed = await transformImage(filePath, queryObject);
|
|
|
|
res.status(200).set(sendFileOptions.headers);
|
|
|
|
res.end(xformed, 'binary');
|
|
|
|
} else {
|
|
|
|
res.status(200).sendFile(filePath, sendFileOptions);
|
|
|
|
}
|
2018-04-29 22:00:41 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = serveFile;
|