Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(isExternal): avoid undefined & improve performance #124

Merged
merged 6 commits into from
Nov 17, 2019
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 11 additions & 17 deletions lib/is_external_link.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,28 @@
'use strict';

const { URL } = require('url');

const urlObj = (str) => {
try {
return new URL(str);
} catch (err) {
return str;
}
};
const { parse, URL } = require('url');

/**
* Check whether the link is external
* @param {String} url The url to check
* @param {String} input The url to check
* @returns {Boolean} True if the link doesn't have protocol or link has same host with config.url
*/

function isExternalLink(url) {
function isExternalLink(input) {
const { config } = this;
const exclude = Array.isArray(config.external_link.exclude) ? config.external_link.exclude
: [config.external_link.exclude];
const data = urlObj(url);
const host = data.hostname;
const sitehost = typeof urlObj(config.url) === 'object' ? urlObj(config.url).hostname : config.url;
const sitehost = parse(config.url).hostname || config.url;
if (!sitehost) return false;

if (!sitehost || typeof data === 'string') return false;
// handle relative url
const data = new URL(input, `http://${sitehost}`);

// handle mailto: javascript: vbscript: and so on
if (data.origin === 'null') return false;

const host = data.hostname;
const exclude = Array.isArray(config.external_link.exclude) ? config.external_link.exclude
: [config.external_link.exclude];

if (exclude && exclude.length) {
for (const i of exclude) {
if (host === i) return false;
Expand Down