Skip to content
Permalink
Browse files

Refactors absoluteURLs template lambda

  • Loading branch information...
davidmerfield committed Aug 29, 2019
1 parent 7c609e8 commit 8c564d98efe4a7ef385f4fe789bc1bfe7bde0375
Showing with 32 additions and 26 deletions.
  1. +32 −26 app/blog/render/retrieve/absoluteURLs.js
@@ -20,41 +20,47 @@ Use it like this:
var cheerio = require("cheerio");
var debug = require("debug")("blot:render:absoluteURLs");

function resolve($, base) {
return function() {
var href = $(this).attr("href");
var src = $(this).attr("src");

// This is a little naive but whatever.
// For example, what about protcolless
// urls like //example.com/site.jpg
if (href && href[0] === "/") {
$(this).attr("href", base + href);
}

if (src && src[0] === "/") {
$(this).attr("src", base + src);
}
};
function absoluteURLs(base, html) {
var $;

try {
$ = cheerio.load(html);
$("[href], [src]").each(function() {
var href = $(this).attr("href");
var src = $(this).attr("src");

// This is a little naive but whatever.
// For example, what about protcol-less
// urls like //example.com/site.jpg
if (href && href[0] === "/") {
$(this).attr("href", base + href);
}

if (src && src[0] === "/") {
$(this).attr("src", base + src);
}
});
html = $.html();
} catch (e) {
debug(e);
}

return html;
}

module.exports = function absoluteURLs(req, callback) {
module.exports = function (req, callback) {
return callback(null, function() {
return function(text, render) {
var $;
var base = req.protocol + "://" + req.get("host");

text = render(text);

try {
$ = cheerio.load(text);
$("[href], [src]").each(resolve($, base));
text = $.html();
} catch (e) {
debug(e);
}
text = absoluteURLs(base, text);

return text;
};
});
};

// We also want to use this function in encodeXML
// so we export it without the callback wrapper.
module.exports.absoluteURLs = absoluteURLs;

0 comments on commit 8c564d9

Please sign in to comment.
You can’t perform that action at this time.