getGQL.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 = 'test461';
  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 {
  46. headers
  47. }
  48. }
  49. }
  50. const getGQL = url => (query, variables= {}) => fetch(url, {
  51. method: 'POST',
  52. headers: checkAuthToken(),
  53. body:JSON.stringify({query, variables})
  54. }).then(res => res.json())
  55. .then(data => data.data[Object.keys(data.data)[0]]);
  56. /*const gql = getGQL(url);
  57. gql(queryCategoryFind).then(data => console.log(data));*/
  58. ;(async () => {
  59. const gql = getGQL(url);
  60. const gqlCategory = (_id) => gql(queryCategory, {categoryId: JSON.stringify([{_id}])});
  61. const gqlGood = (_id) => gql(queryGood, {goodId: JSON.stringify([{_id}])});
  62. const gqlReg = (login, password) => gql(mutationRegistration, {login, password});
  63. const gqlLogin = (login, password) => gql(queryLogin, {login, password});
  64. // категории
  65. console.log(await gql(queryCategories))
  66. // категория по id с товарами
  67. console.log(await gqlCategory(categoryIdVal));
  68. // товар по id с картинками и описанием
  69. console.log(await gqlGood(goodIdVal));
  70. // регистрация
  71. console.log(await gqlReg(login, password));
  72. // логин
  73. console.log(await gqlLogin(login, password));
  74. })();