javascript.md.blade.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. @php
  2. use Knuckles\Scribe\Tools\WritingUtils as u;
  3. /** @var Knuckles\Camel\Output\OutputEndpointData $endpoint */
  4. @endphp
  5. ```javascript
  6. const url = new URL(
  7. "{!! rtrim($baseUrl, '/') !!}/{{ ltrim($endpoint->boundUri, '/') }}"
  8. );
  9. @if(count($endpoint->cleanQueryParameters))
  10. const 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. const 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() || (isset($endpoint->headers['Content-Type']) && $endpoint->headers['Content-Type'] == 'multipart/form-data' && count($endpoint->cleanBodyParameters)))
  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. @if ($endpoint->headers['Content-Type'] == 'application/x-www-form-urlencoded')
  38. let body = "{!! http_build_query($endpoint->cleanBodyParameters, '', '&') !!}";
  39. @else
  40. let body = {!! json_encode($endpoint->cleanBodyParameters, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) !!};
  41. @endif
  42. @endif
  43. fetch(url, {
  44. method: "{{$endpoint->httpMethods[0]}}",
  45. @if(count($endpoint->headers))
  46. headers,
  47. @endif
  48. @if($endpoint->hasFiles() || (isset($endpoint->headers['Content-Type']) && $endpoint->headers['Content-Type'] == 'multipart/form-data' && count($endpoint->cleanBodyParameters)))
  49. body,
  50. @elseif(count($endpoint->cleanBodyParameters))
  51. @if ($endpoint->headers['Content-Type'] == 'application/x-www-form-urlencoded')
  52. body,
  53. @else
  54. body: JSON.stringify(body),
  55. @endif
  56. @endif
  57. }).then(response => response.json());
  58. ```