Last active
May 10, 2021 20:59
-
-
Save cantremember/9ab347971c838272db18a72737a04913 to your computer and use it in GitHub Desktop.
matchURI, using a labeled block
This file contains hidden or 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
import { URL } from 'url'; | |
const DOMAINS = new Set([ 'example.com', 'alternate.net' ]); | |
const SEGMENTS = new Set([ 'query', 'search' ]); | |
export function matchURI(uri) { | |
let id = undefined; | |
let url; | |
try { | |
url = new URL(uri); | |
} | |
catch (err) { | |
return { uri, id, reason: 'error' }; | |
} | |
// match against a valid URL | |
const { hostname, pathname } = url; | |
let reason = 'none'; | |
// 😮 "you can do that ??!" | |
processed: { | |
if (! DOMAINS.has(hostname)) { | |
break processed; | |
} | |
reason = 'hostname'; | |
const pathSegments = pathname.split('/') | |
.filter((segment) => (segment !== '')); | |
if (pathSegments[0] === 'resource') { | |
// "/resource/:id" | |
reason = 'pathname'; | |
id = pathSegments[pathSegments.length - 1]; | |
break processed; | |
} | |
if (pathSegments.some((segment) => SEGMENTS.has(segment))) { | |
// "/operation/query?id=:id" | |
reason = 'param'; // | |
id = url.searchParams.get('id'); | |
break processed; | |
} | |
} | |
return { uri, id, reason }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment