fetch-json.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // fetch wrapper to make simple JSON requests:
  2. // - send the CSRF token in the request
  3. // - set the JSON content-type in the request headers
  4. // - throw errors on non-ok response
  5. // - parse JSON response body, unless response is empty
  6. export function getJSON(path, options) {
  7. return fetchJSON(path, { ...options, method: 'GET' })
  8. }
  9. export function postJSON(path, options) {
  10. return fetchJSON(path, { ...options, method: 'POST' })
  11. }
  12. export function deleteJSON(path, options) {
  13. return fetchJSON(path, { ...options, method: 'DELETE' })
  14. }
  15. export default function fetchJSON(
  16. path,
  17. { body = {}, headers = {}, method = 'GET', ...otherOptions }
  18. ) {
  19. const options = {
  20. ...otherOptions,
  21. headers: {
  22. ...headers,
  23. 'Content-Type': 'application/json',
  24. 'X-Csrf-Token': window.csrfToken
  25. },
  26. method
  27. }
  28. if (method !== 'GET' && method !== 'HEAD') {
  29. options.body = JSON.stringify(body)
  30. }
  31. return fetch(path, options)
  32. .then(response => {
  33. if (!response.ok) throw new Error(response.status)
  34. // get the response as text first as .json() fails on empty responses.
  35. // (e.g. 204 responses)
  36. return response.text()
  37. })
  38. .then(responseText => {
  39. return responseText ? JSON.parse(responseText) : responseText
  40. })
  41. }