help requests.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*Запрос на список корневых категорий
  2. Используем CategoryFind, однако в параметре query используем поиск по полю parent, которое должно быть равно null. (у корневых категорий нет родителя)*/
  3. {
  4. let findCategory = `query baseCategory($searchNullparent: String){
  5. CategoryFind(query: $searchNullparent){
  6. _id name parent {
  7. _id
  8. name
  9. }
  10. }
  11. }`
  12. let variables = {
  13. searchNullparent: JSON.stringify([{ parent: null }])
  14. }
  15. const gql = getGql('http://shop-roles.node.ed.asmer.org.ua/graphql')
  16. gql(findCategory, variables).then(console.log)
  17. }
  18. // getGql - полностью готова
  19. {
  20. function getGql(endpoint) {
  21. let headers = {
  22. 'Content-Type': 'application/json;charset=utf-8',
  23. 'Accept': 'application/json',
  24. }
  25. if ('authToken' in localStorage) {
  26. headers.Authorization = 'Bearer ' + localStorage.authToken
  27. }
  28. return async function gql(query, variables = {}) {
  29. let result = await fetch(endpoint, {
  30. method: 'POST',
  31. headers,
  32. body: JSON.stringify({
  33. query,
  34. variables
  35. })
  36. }).then(res => res.json())
  37. if (('errors' in result) && !('data' in result)) {
  38. throw new Error(JSON.stringify(result.errors))
  39. }
  40. result = Object.values(result.data)[0]
  41. return result
  42. }
  43. }
  44. }
  45. // localStoredReducer
  46. {
  47. function localStoredReducer(originalReducer, localStorageKey) {
  48. function wrapper(state, action) {
  49. if (!state) {
  50. try {
  51. return JSON.parse(localStorage[localStorageKey])
  52. }
  53. catch (error) {
  54. }
  55. }
  56. const newState = originalReducer(state, action)
  57. localStorage[localStoredReducer] = JSON.stringify(newState)
  58. return newState
  59. }
  60. return wrapper
  61. }
  62. }