2018-09-20 16:03:33 +03:00
|
|
|
const crypto = require('crypto');
|
|
|
|
const fs = require('fs-extra');
|
|
|
|
const path = require('path');
|
2018-09-20 21:04:34 +03:00
|
|
|
const config = require('../../../config');
|
|
|
|
const urlService = require('../../../services/url');
|
2015-07-15 19:01:23 +03:00
|
|
|
|
2019-04-23 17:24:33 +03:00
|
|
|
function createPublicFileMiddleware(file, type, maxAge) {
|
2018-09-10 15:07:57 +03:00
|
|
|
let content;
|
2018-09-20 16:03:33 +03:00
|
|
|
const publicFilePath = config.get('paths').publicFilePath;
|
|
|
|
const filePath = file.match(/^public/) ? path.join(publicFilePath, file.replace(/^public/, '')) : path.join(publicFilePath, file);
|
|
|
|
const blogRegex = /(\{\{blog-url\}\})/g;
|
|
|
|
const apiRegex = /(\{\{api-url\}\})/g;
|
2015-12-15 13:41:53 +03:00
|
|
|
|
2017-04-07 15:21:41 +03:00
|
|
|
return function servePublicFile(req, res, next) {
|
2019-04-23 17:24:33 +03:00
|
|
|
if (content) {
|
|
|
|
res.writeHead(200, content.headers);
|
|
|
|
return res.end(content.body);
|
|
|
|
}
|
|
|
|
fs.readFile(filePath, (err, buf) => {
|
|
|
|
if (err) {
|
|
|
|
return next(err);
|
2015-07-15 19:01:23 +03:00
|
|
|
}
|
2019-04-23 17:24:33 +03:00
|
|
|
|
|
|
|
let str = buf.toString();
|
|
|
|
|
|
|
|
if (type === 'text/xsl' || type === 'text/plain' || type === 'application/javascript') {
|
|
|
|
str = str.replace(blogRegex, urlService.utils.urlFor('home', true).replace(/\/$/, ''));
|
|
|
|
str = str.replace(apiRegex, urlService.utils.urlFor('api', {cors: true, version: 'v0.1', versionType: 'content'}, true));
|
|
|
|
}
|
|
|
|
|
|
|
|
content = {
|
|
|
|
headers: {
|
|
|
|
'Content-Type': type,
|
|
|
|
'Content-Length': Buffer.from(str).length,
|
|
|
|
ETag: `"${crypto.createHash('md5').update(str, 'utf8').digest('hex')}"`,
|
|
|
|
'Cache-Control': `public, max-age=${maxAge}`
|
|
|
|
},
|
|
|
|
body: str
|
|
|
|
};
|
|
|
|
res.writeHead(200, content.headers);
|
|
|
|
res.end(content.body);
|
|
|
|
});
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
// ### servePublicFile Middleware
|
|
|
|
// Handles requests to robots.txt and favicon.ico (and caches them)
|
|
|
|
function servePublicFile(file, type, maxAge) {
|
|
|
|
const publicFileMiddleware = createPublicFileMiddleware(file, type, maxAge);
|
|
|
|
|
|
|
|
return function servePublicFile(req, res, next) {
|
|
|
|
if (req.path === '/' + file) {
|
|
|
|
return publicFileMiddleware(req, res, next);
|
2015-07-15 19:01:23 +03:00
|
|
|
} else {
|
2017-11-01 16:44:54 +03:00
|
|
|
return next();
|
2015-07-15 19:01:23 +03:00
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2017-04-07 15:21:41 +03:00
|
|
|
module.exports = servePublicFile;
|
2019-04-23 17:24:33 +03:00
|
|
|
module.exports.servePublicFile = servePublicFile;
|
|
|
|
module.exports.createPublicFileMiddleware = createPublicFileMiddleware;
|