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
|
|
|
|
2017-04-07 15:21:41 +03:00
|
|
|
// ### servePublicFile Middleware
|
2015-07-15 19:01:23 +03:00
|
|
|
// Handles requests to robots.txt and favicon.ico (and caches them)
|
2017-04-07 15:21:41 +03:00
|
|
|
function servePublicFile(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) {
|
2015-12-15 13:41:53 +03:00
|
|
|
if (req.path === '/' + file) {
|
2015-07-15 19:01:23 +03:00
|
|
|
if (content) {
|
|
|
|
res.writeHead(200, content.headers);
|
|
|
|
res.end(content.body);
|
|
|
|
} else {
|
2018-09-20 16:03:33 +03:00
|
|
|
fs.readFile(filePath, (err, buf) => {
|
2015-07-15 19:01:23 +03:00
|
|
|
if (err) {
|
|
|
|
return next(err);
|
|
|
|
}
|
2015-12-15 13:41:53 +03:00
|
|
|
|
|
|
|
if (type === 'text/xsl' || type === 'text/plain' || type === 'application/javascript') {
|
2017-12-11 21:14:05 +03:00
|
|
|
buf = buf.toString().replace(blogRegex, urlService.utils.urlFor('home', true).replace(/\/$/, ''));
|
2019-01-14 21:49:55 +03:00
|
|
|
buf = buf.toString().replace(apiRegex, urlService.utils.urlFor('api', {cors: true, version: 'v0.1', versionType: 'content'}, true));
|
2015-07-15 19:01:23 +03:00
|
|
|
}
|
|
|
|
content = {
|
|
|
|
headers: {
|
|
|
|
'Content-Type': type,
|
|
|
|
'Content-Length': buf.length,
|
2018-09-20 16:03:33 +03:00
|
|
|
ETag: `"${crypto.createHash('md5').update(buf, 'utf8').digest('hex')}"`,
|
|
|
|
'Cache-Control': `public, max-age=${maxAge}`
|
2015-07-15 19:01:23 +03:00
|
|
|
},
|
|
|
|
body: buf
|
|
|
|
};
|
|
|
|
res.writeHead(200, content.headers);
|
|
|
|
res.end(content.body);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
} 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;
|