javascript.blade.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. @php
  2. use Knuckles\Scribe\Tools\WritingUtils as u;
  3. /** @var Knuckles\Camel\Output\OutputEndpointData $endpoint */
  4. @endphp
  5. <pre><code class="language-javascript">
  6. const url = new URL(
  7. "{{ rtrim($baseUrl, '/') }}/{{ ltrim($endpoint->boundUri, '/') }}"
  8. );
  9. @if(count($endpoint->cleanQueryParameters))
  10. let params = {!! u::printQueryParamsAsKeyValue($endpoint->cleanQueryParameters, "\"", ":", 4, "{}") !!};
  11. Object.keys(params)
  12. .forEach(key => url.searchParams.append(key, params[key]));
  13. @endif
  14. @if(!empty($endpoint->headers))
  15. let headers = {
  16. @foreach($endpoint->headers as $header => $value)
  17. "{{$header}}": "{{$value}}",
  18. @endforeach
  19. @empty($endpoint->headers['Accept'])
  20. "Accept": "application/json",
  21. @endempty
  22. };
  23. @endif
  24. @if($endpoint->hasFiles())
  25. const body = new FormData();
  26. @foreach($endpoint->cleanBodyParameters as $parameter => $value)
  27. @foreach( u::getParameterNamesAndValuesForFormData($parameter, $value) as $key => $actualValue)
  28. body.append('{!! $key !!}', '{!! $actualValue !!}');
  29. @endforeach
  30. @endforeach
  31. @foreach($endpoint->fileParameters as $parameter => $value)
  32. @foreach( u::getParameterNamesAndValuesForFormData($parameter, $value) as $key => $file)
  33. body.append('{!! $key !!}', document.querySelector('input[name="{!! $key !!}"]').files[0]);
  34. @endforeach
  35. @endforeach
  36. @elseif(count($endpoint->cleanBodyParameters))
  37. let body = {!! json_encode($endpoint->cleanBodyParameters, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) !!}
  38. @endif
  39. fetch(url, {
  40. method: "{{$endpoint->httpMethods[0]}}",
  41. @if(count($endpoint->headers))
  42. headers,
  43. @endif
  44. @if($endpoint->hasFiles())
  45. body,
  46. @elseif(count($endpoint->cleanBodyParameters))
  47. body: JSON.stringify(body),
  48. @endif
  49. }).then(response => response.json());
  50. </code></pre>