getGQL_error.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. const queryCategories = `query categoriesQuery {
  2. CategoryFind(query:"[{}]") {
  3. _id
  4. name
  5. }
  6. }`;
  7. const queryCategory = `query categoryQuery($categoryId:String) {
  8. CategoryFindOne(query:$categoryId) {
  9. _id name goods {
  10. _id
  11. }
  12. }
  13. }`;
  14. const queryGood = `query goodQuery($goodId:String) {
  15. GoodFindOne(query:$goodId) {
  16. _id description images {
  17. url
  18. }
  19. }
  20. }`;
  21. const mutationRegistration = `mutation register($login:String, $password:String) {
  22. UserUpsert(user:{login:$login, password:$password}) {
  23. _id login createdAt
  24. }
  25. }`;
  26. const queryLogin = `query log($login:String, $password:String) {
  27. login(login:$login, password:$password)
  28. }`;
  29. const categoryIdVal = '6262ca7dbf8b206433f5b3d1';
  30. const goodIdVal = '62d3099ab74e1f5f2ec1a125';
  31. const login = 'test462';
  32. const password = '123123123';
  33. const url = 'http://shop-roles.node.ed.asmer.org.ua/graphql';
  34. const checkAuthToken = () => {
  35. const headers = {
  36. "Content-Type": "application/json",
  37. "Accept": "application/json",
  38. }
  39. if(localStorage.getItem('authToken')) {
  40. return {
  41. ...headers,
  42. "Authorization": `Bearer ${localStorage.getItem('authToken')}`
  43. }
  44. } else {
  45. return headers
  46. }
  47. }
  48. const getGQL = url => (query, variables= {}) => fetch(url, {
  49. method: 'POST',
  50. headers: checkAuthToken(),
  51. body:JSON.stringify({query, variables})
  52. }).then(res => res.json())
  53. .then(data => {
  54. try {
  55. if(!data.data && data.errors) {
  56. throw new SyntaxError(`SyntaxError - ${JSON.stringify(Object.values(data.errors)[0])}`);
  57. }
  58. return data.data[Object.keys(data.data)[0]];
  59. } catch (e) {
  60. console.error(e);
  61. }
  62. });
  63. /*const gql = getGQL(url);
  64. gql(queryCategoryFind).then(data => console.log(data));*/
  65. ;(async () => {
  66. const gql = getGQL(url);
  67. const gqlCategory = (_id) => gql(queryCategory, {categoryId: JSON.stringify([{_id}])});
  68. const gqlGood = (_id) => gql(queryGood, {goodId: JSON.stringify([{_id}])});
  69. const gqlReg = (login, password) => gql(mutationRegistration, {login, password});
  70. const gqlLogin = (login, password) => gql(queryLogin, {login, password});
  71. // категории
  72. console.log(await gql(queryCategories))
  73. // категория по id с товарами
  74. console.log(await gqlCategory(categoryIdVal));
  75. // товар по id с картинками и описанием
  76. console.log(await gqlGood(goodIdVal));
  77. // регистрация
  78. console.log(await gqlReg(login, password));
  79. // логин
  80. console.log(await gqlLogin(login, password));
  81. })();