Created
January 24, 2022 03:04
-
-
Save DavidWells/62faf928f5711a124f3b4d30d195ac87 to your computer and use it in GitHub Desktop.
Resolve API URL from string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { URL } = require('url') | |
const assert = require('assert') | |
const DEFAULT_BASE = 'https://api.github.com' | |
/* Zero dependency backward compatible url parser */ | |
function parseUrl(url) { | |
const match = url.match(/^(https?)?(?:[\:\/]*)([a-z0-9\.-]*)(?:\:(\d+))?(\/[^?#]*)?(?:\?([^#]*))?(?:#(.*))?$/i) | |
return { | |
protocol: match[1] || '', | |
host: match[2] || '', | |
port: match[3] || '', | |
path: match[4] || '', | |
query: match[5] || '', | |
fragment: match[6] || '', | |
} | |
} | |
function getHost(url) { | |
const data = parseUrl(url) | |
let pathName = data.path | |
if (!data.protocol && !data.path && url.indexOf('.') > -1) { | |
pathName = data.host | |
} | |
if (!data.protocol && url.indexOf('.') === -1) { | |
pathName = url | |
} | |
return { | |
path: pathName, | |
base: (!data.protocol) ? DEFAULT_BASE : `${data.protocol}://${data.host}` | |
} | |
} | |
function resolvePath(pathOrUrl) { | |
const urlInfo = getHost(pathOrUrl) | |
return new URL(urlInfo.path, urlInfo.base) | |
} | |
const x = new URL('/lol', 'https://api.github.com') | |
console.log(x instanceof URL) | |
// console.log(new URL('/lol', 'https://api.github.com')) | |
// console.log(resolvePath('https://api.github.com/nice')) | |
// console.log(resolvePath('https://api.github.com/nice')) | |
// console.log(resolvePath('/coocococ/cool')) | |
assert.equal(resolvePath('https://api.github.com/nice').pathname, '/nice') | |
assert.equal(resolvePath('api.github.com/nice').pathname, '/nice') | |
assert.equal(resolvePath('nice').pathname, '/nice') | |
assert.equal(resolvePath('/nice').pathname, '/nice') | |
assert.equal(resolvePath('wow/nice').pathname, '/wow/nice') | |
assert.equal(resolvePath('/wow/nice').pathname, '/wow/nice') | |
assert.equal(resolvePath('https://api.github.com/wow/nice').pathname, '/wow/nice') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment