script.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. const getGQL = url =>
  2. (query, variables) => fetch(url, {
  3. method: 'POST',
  4. headers: { //заголовок content-type
  5. "Content-Type": "application/json",
  6. ...(localStorage.authToken ? {"Authorization": "Bearer " + localStorage.authToken} : {})
  7. },
  8. body: JSON.stringify({query, variables}) //body с ключами query и variables
  9. }).then(res => res.json())
  10. .then(data => {
  11. if (data.data){
  12. console.log(data);
  13. return data.data;
  14. }
  15. else throw new Error(JSON.stringify(data.errors))
  16. })
  17. const backendURL = 'http://shop-roles.asmer.fs.a-level.com.ua'
  18. const gql = getGQL(backendURL + '/graphql')
  19. function register(login, password) {
  20. return gql(
  21. `mutation reg($login:String, $password:String) {UserUpsert(user: {login:$login, password: $password}) {_id login} }`,
  22. { login: login, password: password }
  23. );
  24. }
  25. register("Natasha", "12345").then(res=>console.log(res));
  26. const login = (login, password) => {
  27. return gql(` query log ($login:String, $password:String){
  28. login(login:$login, password: $password) }`,
  29. {login:login, password:password})
  30. }
  31. login("Natasha","12345").then(res=>console.log(res))
  32. const rootCats= () =>
  33. gql(`query {
  34. CategoryFind(query: "[{\\"parent\\":null}]"){
  35. _id name
  36. }
  37. }`)
  38. rootCats().then(res=>console.log(res))
  39. const findCatById=(_id)=> gql(`query catById($q: String){
  40. CategoryFindOne(query: $q){
  41. _id name goods {
  42. _id name price images {
  43. url
  44. }
  45. }
  46. }
  47. }`, {q: JSON.stringify([{_id}])} )
  48. findCatById("61715f99ef4e1b3e3b67703e").then(res=>console.log(res))
  49. const findGoodById=(_id)=> gql(`
  50. query goodById($q: String){
  51. GoodFindOne(query:$q){
  52. _id
  53. name
  54. price
  55. description
  56. categories{_id name}
  57. }
  58. } `, {q: JSON.stringify([{_id}])})
  59. findGoodById("61782338ef4e1b3e3b677079").then(res=>console.log(res))