Skip to content

Commit

Permalink
Try It Out: Restore sample request/response after cancel
Browse files Browse the repository at this point in the history
  • Loading branch information
shalvah committed Jun 30, 2021
1 parent 10cc5b0 commit 25aaabb
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 47 deletions.
56 changes: 15 additions & 41 deletions resources/js/tryitout.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ function cancelTryOut(endpointId) {
executeBtn.hidden = true;
executeBtn.textContent = "Send Request 💥";
document.querySelector(`#btn-canceltryout-${endpointId}`).hidden = true;
// hide inputs
// Hide inputs
document.querySelectorAll(`input[data-endpoint=${endpointId}],label[data-endpoint=${endpointId}]`)
.forEach(el => el.hidden = true);
document.querySelectorAll(`#form-${endpointId} details`)
Expand All @@ -34,21 +34,8 @@ function cancelTryOut(endpointId) {
document.querySelector('#execution-error-' + endpointId).hidden = true;

// Revert to sample code blocks
const query = new URLSearchParams(window.location.search);
const languages = JSON.parse(document.querySelector('body').dataset.languages);
const currentLanguage = languages.find(l => query.has(l)) || languages[0];

let codeblock = getPreviousSiblingUntil(document.querySelector('#form-' + endpointId), 'blockquote,pre', 'h2');
while (codeblock != null) {
if (codeblock.nodeName === 'PRE') {
if (codeblock.querySelector('code.language-' + currentLanguage)) {
codeblock.style.display = 'block';
}
} else {
codeblock.style.display = 'block';
}
codeblock = getPreviousSiblingUntil(codeblock, 'blockquote,pre', 'h2');
}
document.querySelector('#example-requests-' + endpointId).hidden = false;
document.querySelector('#example-responses-' + endpointId).hidden = false;
}

function makeAPICall(method, path, body, query, headers) {
Expand Down Expand Up @@ -89,24 +76,20 @@ function makeAPICall(method, path, body, query, headers) {
.then(response => Promise.all([response.status, response.text(), response.headers]));
}

function hideCodeSamples(form) {
let codeblock = getPreviousSiblingUntil(form, 'blockquote,pre', 'h2');
while (codeblock != null) {
codeblock.style.display = 'none';
codeblock = getPreviousSiblingUntil(codeblock, 'blockquote,pre', 'h2');
}
function hideCodeSamples(endpointId) {
document.querySelector('#example-requests-' + endpointId).hidden = true;
document.querySelector('#example-responses-' + endpointId).hidden = true;
}

function handleResponse(form, endpointId, response, status, headers) {
hideCodeSamples(form);
function handleResponse(endpointId, response, status, headers) {
hideCodeSamples(endpointId);

// Hide error views
document.querySelector('#execution-error-' + endpointId).hidden = true;


const responseContentEl = document.querySelector('#execution-response-content-' + endpointId);

// prettify it if it's JSON
// Prettify it if it's JSON
let isJson = false;
try {
const jsonParsed = JSON.parse(response);
Expand All @@ -125,8 +108,8 @@ function handleResponse(form, endpointId, response, status, headers) {
statusEl.scrollIntoView({behavior: "smooth", block: "center"});
}

function handleError(form, endpointId, err) {
hideCodeSamples(form);
function handleError(endpointId, err) {
hideCodeSamples(endpointId);
// Hide response views
document.querySelector('#execution-results-' + endpointId).hidden = true;

Expand Down Expand Up @@ -194,28 +177,19 @@ async function executeTryOut(endpointId, form) {
if (authHeaderEl) headers[authHeaderEl.name] = authHeaderEl.dataset.prefix + authHeaderEl.value;
}
// When using FormData, the browser sets the correct content-type + boundary
if (headers['Content-Type'] === "multipart/form-data") {
if (body instanceof FormData) {
delete headers['Content-Type'];
}

makeAPICall(form.dataset.method, path, body, query, headers)
.then(([responseStatus, responseContent, responseHeaders]) => {
handleResponse(form, endpointId, responseContent, responseStatus, responseHeaders)
handleResponse(endpointId, responseContent, responseStatus, responseHeaders)
})
.catch(err => {
console.log("Error while making request: ", err);
handleError(form, endpointId, err);
handleError(endpointId, err);
})
.finally(() => {
executeBtn.textContent = "Send Request 💥";
});
}

function getPreviousSiblingUntil(elem, siblingSelector, stopSelector) {
let sibling = elem.previousElementSibling;
while (sibling) {
if (sibling.matches(siblingSelector)) return sibling;
if (sibling.matches(stopSelector)) return null;
sibling = sibling.previousElementSibling;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@
);
@if(count($endpoint->cleanQueryParameters))

let params = {!! u::printQueryParamsAsKeyValue($endpoint->cleanQueryParameters, "\"", ":", 4, "{}") !!};
const params = {!! u::printQueryParamsAsKeyValue($endpoint->cleanQueryParameters, "\"", ":", 4, "{}") !!};
Object.keys(params)
.forEach(key => url.searchParams.append(key, params[key]));
@endif

@if(!empty($endpoint->headers))
let headers = {
const headers = {
@foreach($endpoint->headers as $header => $value)
"{{$header}}": "{{$value}}",
@endforeach
Expand Down
12 changes: 8 additions & 4 deletions resources/views/themes/default/endpoint.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,17 @@

{!! Parsedown::instance()->text($endpoint->metadata->description ?: '') !!}

<span id="example-requests-{!! $endpoint->endpointId() !!}">
<blockquote>Example request:</blockquote>

@foreach($metadata['example_languages'] as $language)

@include("scribe::partials.example-requests.$language")

@endforeach
</span>

<span id="example-responses-{!! $endpoint->endpointId() !!}">
@if($endpoint->isGet() || $endpoint->hasResponses())
@foreach($endpoint->responses as $response)
<blockquote>
Expand Down Expand Up @@ -49,16 +52,17 @@
</pre>
@endforeach
@endif
<div id="execution-results-{{ $endpoint->endpointId() }}" hidden>
</span>
<span id="execution-results-{{ $endpoint->endpointId() }}" hidden>
<blockquote>Received response<span
id="execution-response-status-{{ $endpoint->endpointId() }}"></span>:
</blockquote>
<pre class="json"><code id="execution-response-content-{{ $endpoint->endpointId() }}"></code></pre>
</div>
<div id="execution-error-{{ $endpoint->endpointId() }}" hidden>
</span>
<span id="execution-error-{{ $endpoint->endpointId() }}" hidden>
<blockquote>Request failed with error:</blockquote>
<pre><code id="execution-error-message-{{ $endpoint->endpointId() }}"></code></pre>
</div>
</span>
<form id="form-{{ $endpoint->endpointId() }}" data-method="{{ $endpoint->httpMethods[0] }}"
data-path="{{ $endpoint->uri }}"
data-authed="{{ $endpoint->metadata->authenticated ? 1 : 0 }}"
Expand Down

0 comments on commit 25aaabb

Please sign in to comment.