Created
July 20, 2017 14:36
-
-
Save KOBA789/c975cd12675a794daab0ecba2aa6540b to your computer and use it in GitHub Desktop.
Type-safe URL Template
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
class PathTemplate<N extends string> { | |
constructor(public fragments: string[], public paramNames: N[]) {} | |
render(params: {[_ in N]: string}) { | |
const buf = [this.fragments[0]]; | |
for (let i = 0; i < this.paramNames.length; ++i) { | |
buf.push(params[this.paramNames[i]]); | |
buf.push(this.fragments[i + 1]); | |
} | |
return buf.join(''); | |
} | |
} | |
function path<N extends string>(strs: TemplateStringsArray, ...ns: N[]): PathTemplate<N> { | |
return new PathTemplate<N>([...strs], ns); | |
} | |
const template = path`/users/${'user_id'}/articles/${'article_id'}/comments/${'id'}`; | |
console.log(template.render({ | |
user_id: '1', | |
article_id: '2', | |
id: '3', | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment