javascript.blade.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. ```javascript
  2. const url = new URL(
  3. "{{ rtrim($baseUrl, '/') }}/{{ ltrim($route['boundUri'], '/') }}"
  4. );
  5. @if(count($route['cleanQueryParameters']))
  6. let params = {!! \Knuckles\Scribe\Tools\WritingUtils::printQueryParamsAsKeyValue($route['cleanQueryParameters'], "\"", ":", 4, "{}") !!};
  7. Object.keys(params)
  8. .forEach(key => url.searchParams.append(key, params[key]));
  9. @endif
  10. @if(!empty($route['headers']))
  11. let headers = {
  12. @foreach($route['headers'] as $header => $value)
  13. "{{$header}}": "{{$value}}",
  14. @endforeach
  15. @if(!array_key_exists('Accept', $route['headers']))
  16. "Accept": "application/json",
  17. @endif
  18. };
  19. @endif
  20. @if(count($route['fileParameters']))
  21. const body = new FormData();
  22. @foreach($route['cleanBodyParameters'] as $parameter => $value)
  23. @foreach( \Knuckles\Scribe\Tools\WritingUtils::getParameterNamesAndValuesForFormData($parameter,$value) as $key => $actualValue)
  24. body.append('{!! $key !!}', '{!! $actualValue !!}');
  25. @endforeach
  26. @endforeach
  27. @foreach($route['fileParameters'] as $parameter => $file)
  28. body.append('{!! $parameter !!}', document.querySelector('input[name="{!! $parameter !!}"]').files[0]);
  29. @endforeach
  30. @elseif(count($route['cleanBodyParameters']))
  31. let body = {!! json_encode($route['cleanBodyParameters'], JSON_PRETTY_PRINT) !!}
  32. @endif
  33. fetch(url, {
  34. method: "{{$route['methods'][0]}}",
  35. @if(count($route['headers']))
  36. headers: headers,
  37. @endif
  38. @if(count($route['fileParameters']) || count($route['cleanBodyParameters']))
  39. body: body
  40. @endif
  41. })
  42. .then(response => response.json())
  43. .then(json => console.log(json));
  44. ```