spee.ch/server/controllers/assets/utils/serveFile.js

48 lines
1.4 KiB
JavaScript
Raw Normal View History

2018-04-29 22:00:41 +02:00
const logger = require('winston');
2019-02-20 07:30:46 +01:00
const transformImage = require('./transformImage');
2019-02-24 07:23:56 +01:00
2019-02-20 07:30:46 +01:00
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
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
},
};
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;