Skip to content

Commit

Permalink
feat(full_url_for): bring up a new helper (#84)
Browse files Browse the repository at this point in the history
* feat(full_url_for): bring up a new helper
  • Loading branch information
SukkaW authored and curbengh committed Sep 14, 2019
1 parent 8daee5b commit 2de7c15
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 0 deletions.
14 changes: 14 additions & 0 deletions README.md
Expand Up @@ -61,6 +61,20 @@ Escapes diacritic characters in a string.

Escapes HTML entities in a string.

### full_url_for(path)

Returns a url with the config.url prefixed. Output is [encoded](#encodeurlstr) automatically.

``` yml
_config.yml
url: https://example.com/blog # example
```

``` js
full_url_for('/a/path')
// https://example.com/blog/a/path
```

### hash(str)

Generates SHA1 hash.
Expand Down
18 changes: 18 additions & 0 deletions lib/full_url_for.js
@@ -0,0 +1,18 @@
'use strict';

const { parse } = require('url');
const encodeURL = require('./encode_url');

function fullUrlForHelper(path = '/') {
if (path.startsWith('//')) return path;
const { config } = this;
const data = parse(path);

// Exit if this is an external path
if (data.protocol) return path;

path = encodeURL(config.url + `/${path}`.replace(/\/{2,}/g, '/'));
return path;
}

module.exports = fullUrlForHelper;
1 change: 1 addition & 0 deletions lib/index.js
Expand Up @@ -10,6 +10,7 @@ exports.encodeURL = require('./encode_url');
exports.escapeDiacritic = require('./escape_diacritic');
exports.escapeHTML = require('./escape_html');
exports.escapeRegExp = require('./escape_regexp');
exports.full_url_for = require('./full_url_for');
exports.hash = hash.hash;
exports.HashStream = hash.HashStream;
exports.highlight = require('./highlight');
Expand Down
40 changes: 40 additions & 0 deletions test/full_url_for.spec.js
@@ -0,0 +1,40 @@
'use strict';

describe('full_url_for', () => {
const ctx = {
config: {}
};

const fullUrlFor = require('../lib/full_url_for').bind(ctx);

it('internal url - root directory', () => {
ctx.config.url = 'https://example.com';
fullUrlFor('index.html').should.eql(ctx.config.url + '/index.html');
fullUrlFor('/').should.eql(ctx.config.url + '/');
});

it('internal url - subdirectory', () => {
ctx.config.url = 'https://example.com/blog';
fullUrlFor('index.html').should.eql(ctx.config.url + '/index.html');
fullUrlFor('/').should.eql(ctx.config.url + '/');
});

it('internal url - no duplicate slash', () => {
ctx.config.url = 'https://example.com';
fullUrlFor('/index.html').should.eql('https://example.com/index.html');
});

it('external url', () => {
[
'https://hexo.io/',
'//google.com/'
].forEach(url => {
fullUrlFor(url).should.eql(url);
});
});

it('only hash', () => {
ctx.config.url = 'https://example.com/blog';
fullUrlFor('#test').should.eql(ctx.config.url + '/#test');
});
});

0 comments on commit 2de7c15

Please sign in to comment.