Split responsibilities
c089 opened this issue · comments
Just a quick thought I had when I read the changelog for 1.3.0: To me it seems to have two responsibilities and as such violate the SRP:
- prevent security issues by espacing unsafe characters
- serialize data that is not compatible with JSON
Instead of having a isJSON
flag that controls wether one of those functionalities should be ignored, there could be two functions:
const escapeUnsafe = (o) => ...
const serializeNonJSON = (o) =>
And a function that has the current behaviour could simply be composed of those functions:
const serializeJavascript = compose(escapeUnsafe, serializeNonJSON);
(For performance reasons a different implementation may be necessary in JS of course)
I agree that the option is not the best API, but it's a tradeoff for speed. And the string has to be escaped before the functions and regexp are added back into it after passing though JSON.stringify()
. The order is:
JSON.stringify()
with replacer that inserts did placeholder strings for regexps and functions.- Escape string to prevent XSS in
<script>
context - Serialize regexps and functions and insert them where their placeholders are.
Since the escaping happens in the middle, the functions don't compose very cleanly.
👍 Makes sense, was just curious to discuss my understanding of the design :)