Created with <3 with dartpad.dev.
Created
May 10, 2023 22:49
-
-
Save Cierra-Runis/b0819fe7ab886f6a3cb9e1d102092d91 to your computer and use it in GitHub Desktop.
tangled-rose-8335
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
void main() { | |
final templateUrl = '{host}/api/v3/{container}/{resourceId}'; | |
final params = <String, dynamic>{ | |
'host': 'www.api.com', | |
'container': 'books', | |
'resourceId': 10 | |
}; | |
print(templateUrl.asTemplate(params)); // www.api.com/api/v3/books/10 | |
} | |
extension TemplateString on String { | |
String asTemplate(Map<String, dynamic> params) { | |
// check first | |
params.forEach((key, value) { | |
if (!RegExp(r'^[a-zA-Z_$][a-zA-Z0-9_$]*$').hasMatch(key)) { | |
throw Exception( | |
'check your params, which "$key" should match dart variable naming rule', | |
); | |
} | |
}); | |
return replaceAllMapped(RegExp(r'{(.*?)}'), (match) { | |
final key = match.group(1); | |
final value = params[key]; | |
if (value == null) { | |
throw Exception('Key "$key" not found in replace dictionary'); | |
} | |
return value.toString(); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment