script.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. let url = 'http://shop-roles.asmer.fs.a-level.com.ua/graphql';
  2. const getGQL = url => (query,variables = {}) =>
  3. fetch(url, {
  4. method : 'POST',
  5. headers : {
  6. 'Content-Type' : 'application/json',
  7. 'Accept' : 'application/json',
  8. ...(localStorage.authToken ? {"Authorization": "Bearer " + localStorage.authToken} : {})
  9. },
  10. body : JSON.stringify({query,variables})
  11. }
  12. ).then(res => res.json())
  13. .then((data)=>{
  14. if(data.errors && !data.data){
  15. throw new Error(JSON.stringify(data.errors))
  16. } else {
  17. let ar = Object.values(data.data)
  18. return ar[0]
  19. }
  20. }).then((data) => data);
  21. const gql = getGQL(url);
  22. async function login(log,pass){
  23. let token = await gql(`query login($login:String, $password:String){
  24. login(login:$login, password : $password)
  25. }`, {login : log, password : pass});
  26. localStorage.authToken = await token;
  27. }
  28. async function register(log,pass){
  29. let data = await gql( `mutation register($login: String, $password: String) {
  30. UserUpsert(user: {login: $login, password: $password}) {
  31. _id
  32. login
  33. }
  34. }`, {login : log, password : pass});
  35. console.log(data);
  36. }
  37. async function findCat(id){ // + все гуды этой категории (айди и имя)
  38. let data = await gql( `query findCatOne($q1: String) {
  39. CategoryFindOne(query: $q1) {
  40. name
  41. _id
  42. goods {
  43. _id
  44. name
  45. }
  46. }
  47. }`, {q1 : JSON.stringify([{_id: id}])});
  48. console.log(data);
  49. }
  50. async function newOrder(){
  51. let data = await gql( `mutation newOrder($order: OrderInput) {
  52. OrderUpsert(order: $order) {
  53. _id
  54. total
  55. }
  56. }`, {order :{
  57. orderGoods: [
  58. {count: 2, good: {_id: "5dc4a3e15df9d670df48cc6b"}},
  59. {count: 3, good: {_id: "5e247bbb56d8f720513e6ce2"}}
  60. ]
  61. }})
  62. console.log(data) ///=====>{_id: '61db3220c750c12ba6ba4fa4', total: 23997}
  63. }
  64. async function findGoodId(id){
  65. let data = await gql(`query findGood($goodId: String) {
  66. GoodFindOne(query: $goodId) {
  67. name
  68. price
  69. }
  70. }`, {goodId : JSON.stringify([{_id: id}])})
  71. console.log(data) //=====>>>{name: 'Морс смородиновый (1 л)', price: 60}
  72. }
  73. register('qwewe12334', '445224')
  74. login("user24049312", "240493");
  75. findCat("5dc94bd00e36db246e3049ee");
  76. newOrder();
  77. findGoodId("5dcac4ce6d09c45440d14cf9");