Last active
June 6, 2019 17:19
-
-
Save 7jpsan/b51fc00fc8c956b22d45558421cd1ee1 to your computer and use it in GitHub Desktop.
Typescript string template engine
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 { cloneDeep } from 'lodash'; | |
| class UrlTemplateService { | |
| private readonly urlsMap = { | |
| serviceA: { | |
| example1: (p: { customerCode: string }) => this.replace('one.parameter/${customerCode}', p), | |
| pathB: (p: { more: string, parameter: string }) => this.replace('two.more.example/${more}/${parameter}/${more}', p) | |
| }, | |
| serviceB: { | |
| create: () => 'no.parameter.example', | |
| } | |
| }; | |
| public getMap(){ | |
| return cloneDeep(this.urlsMap); | |
| } | |
| private replace(url: string, params: { [key: string]: string }) { | |
| let finalUrl = url; | |
| const keys = Object.keys(params); | |
| for (const k of keys) { | |
| const re = new RegExp("\\$\\{" + k+ "\\}","g"); | |
| finalUrl = finalUrl.replace(re, params[k]); | |
| } | |
| return finalUrl; | |
| } | |
| } | |
| // Then it can be inject/used like this: | |
| const urlMap = new UrlTemplateService().getMap(); | |
| console.log(urlMap.serviceA.pathB({more: 'mm', parameter: 'pp'})); | |
| // two.more.example/mm/pp/mm |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment