Fetch reformat
by jonahe
HTML
<section>
<label for="rawInput">Raw input</label>
<textarea rows=10 cols="400" id="rawInput" type="text"></textarea>
</section>
<button onclick="window.replaceBody()">
Replace body
</button>
<pre id="output">
test
</pre>
<section>
<textarea rows=10 cols="400" id="outputPure"></textarea>
</section>
CSS
section {
display: flex;
align-items: center;
}
label {
padding: 5px;
}
pre {
display: none;
background: black;
color: yellow;
height: 100%;
}
#outputPure {
background: lightslategrey;
color: yellow;
padding: 20px;
font-family: monospace;
}
JavaScript
const startInput = `fetch("https://test.quiddity.se/api/members", {"credentials":"include","headers":{"accept":"application/json, text/plain, */*","accept-language":"sv-SE,sv;q=0.9,en-SE;q=0.8,en;q=0.7,en-US;q=0.6","cache-control":"no-cache","content-type":"application/json","pragma":"no-cache","sec-fetch-dest":"empty","sec-fetch-mode":"cors","sec-fetch-site":"same-origin"},"referrer":"https://test.quiddity.se/admin/sessions/5e78dbae91cea05499966e26","referrerPolicy":"no-referrer-when-downgrade","body":"{\"id\":\"5e7c6fd96c5835119e348b57\",\"group\":\"5ea025acd3e12840a134eced\"}","method":"PUT","mode":"cors"});`;
function getRawInput() {
return eval(`\`${ document.getElementById("rawInput").value}\``);
}
/*
(function init() {
document.getElementById("rawInput").value = startInput;
})();
*/
window.replaceBody = function replaceBody() {
const bodyStringInner = getBodyString({inner: true});
const formattedBody = JSON.stringify( JSON.parse(bodyStringInner), null, 2 );
const newBody = `JSON.stringify(${
formattedBody
})
`;
const valueToReplace = getBodyString({inner: false});
const originalCode = getRawInput();
document.getElementById("output").innerHTML = originalCode.replace(valueToReplace, newBody);
document.getElementById("outputPure").value = originalCode.replace(valueToReplace, newBody);
}
function getBodyString({inner = false}) {
const bodyStringRegex = /"body":"(?<bodyString>.*)","method"/g;
const bodyStringPlusExtraQuotesRegex = /"body":(?<bodyString>.*),"method"/g;
const rawInput = getRawInput();
const { groups } = inner ? bodyStringRegex.exec(rawInput) : bodyStringPlusExtraQuotesRegex.exec(rawInput);
const { bodyString } = groups;
return bodyString;
}
window.handleDone = function handleDone() {
window.parsedFetch = document.getElementById('output');
window.prompt('paste in console to copy result', `copy(window.parsedFetch)`);
}