getGql.js 762 B

123456789101112131415161718192021222324
  1. import { backURL } from '../constants'
  2. const getGQL =
  3. (url) =>
  4. async (query, variables = {}) => {
  5. const incomingData = await fetch(url, {
  6. method: 'POST',
  7. headers: {
  8. 'Content-Type': 'application/json',
  9. ...(localStorage.authToken
  10. ? { Authorization: 'Bearer ' + localStorage.authToken }
  11. : {}),
  12. },
  13. body: JSON.stringify({ query, variables }),
  14. })
  15. const obj = await incomingData.json()
  16. if (!obj.data && obj.errors) {
  17. throw new Error(JSON.stringify(obj.errors))
  18. } else {
  19. return obj.data[Object.keys(obj.data)[0]]
  20. }
  21. }
  22. export const gql = getGQL(backURL + 'graphql')