Skip to content

Instantly share code, notes, and snippets.

@benhorst
Last active January 8, 2020 16:49
Show Gist options
  • Save benhorst/51a57ef34a3ade3d8e550d2f44119cf2 to your computer and use it in GitHub Desktop.
Save benhorst/51a57ef34a3ade3d8e550d2f44119cf2 to your computer and use it in GitHub Desktop.
// this could definitely be moved out to a helper/util.
// I'd consider this a better and less fallible approach to our previous ideas of using {{token}}.
const defaultValue = '';
// see MDN reference on TaggedTemplates for how the strings&keys work.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
const urlTemplate = (strings, ...keys) =>
// returns a function that accepts a property bag (presumably to fill in the tokens)
(props) =>
// start with the first string, then map each tokenized Key to a tuple of: `Properties[Key], NextString`
// now you have [string0] + [ [value, string1], [value, string2], ... ].flat() and you slap it all together with .join
[strings[0]].concat(
keys.map((k, i) => [
(props[k] || defaultValue),
strings[i+1]
]).flat()
).join('');
// say you want to templatize a url
// the interspersed ${string} become tokens in the template
// that way, we can replaced those tokens with values from an object
// this guarantees that parsing the string as tokens succeeds
// (eg: doing `foo/{{bar}}/baz` runs the risk of needing {{}} characters and having to escape, however small.)
const template = urlTemplate`/engage/tool/${'toolName'}?patientId=${'patientId'}&encounterId=${'encounterId'}`
// etc. Yes, I know that `${'xyz'}` looks funny. pls see references
// later on in your existing code we should use the standard set of session/context properties to send to the urlreplacer function
const context = { encounterId: activeEncounterId, patientId, userId: activeUserId };
const resultingUrl = template(context);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment