Permalink
Browse files

Added method to resolve relative links. Useful for RSS feeds etc.

  • Loading branch information...
davidmerfield committed Dec 6, 2018
1 parent 3140a25 commit 00ab16f4a637e0d36cb22572878437fc488a7bf9
Showing with 44 additions and 0 deletions.
  1. +44 −0 app/blog/render/retrieve/resolveRelativeLinks.js
@@ -0,0 +1,44 @@
var cheerio = require("cheerio");
// Used to resolve relative URLs
// Useful for RSS feeds
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);
}
};
}
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) {
// do nothing
}
return text;
};
});
};

0 comments on commit 00ab16f

Please sign in to comment.