main.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. const getGQL = url =>
  2. (query, variables) =>
  3. fetch(url , {
  4. method: 'POST',
  5. headers: {
  6. "content-type": "application/json",
  7. ...(localStorage.authToken ? { Authorization: "Bearer " + localStorage.authToken } : {})
  8. },
  9. body: JSON.stringify({query, variables})
  10. }).then(res => res.json())
  11. let gql = getGQL("http://shop-roles.asmer.fs.a-level.com.ua/graphql")
  12. //регистрация
  13. let reg = async(login, password) => {
  14. let query = `mutation reg($login:String, $password:String) {
  15. UserUpsert(user:{
  16. login: $login,
  17. password: $password
  18. }){
  19. _id
  20. }
  21. }`
  22. let variables = {"login":login, "password":password}
  23. let res = await gql(query, variables)
  24. console.log(res)
  25. return res
  26. }
  27. //логин
  28. let login = async(login, password) => {
  29. let query = `query login($login:String, $password:String) {
  30. login(login: $login, password: $password)
  31. }`
  32. let variables = {"login":login, "password":password}
  33. let token = await gql(query, variables)
  34. console.log(token)
  35. localStorage.authToken = token.data.login
  36. }
  37. //отправка заказа
  38. let newOrder = async(obj) => {
  39. let option = Object.entries(obj)
  40. let orderGoods = []
  41. for (let key of option) {
  42. let i = {
  43. "count": key[1],
  44. "good": {"_id": key[0]}
  45. }
  46. orderGoods.push(i)
  47. }
  48. let query = `mutation newOrder($order:OrderInput) {
  49. OrderUpsert(order:$order) {
  50. _id
  51. }
  52. }`
  53. let variables = {
  54. "order": {"orderGoods": orderGoods}
  55. }
  56. let res = await gql(query, variables)
  57. console.log(res)
  58. return res
  59. }
  60. //получениe всех заказов
  61. let getOrders = async() => {
  62. let query = `query orders {
  63. OrderFind(query:"[{}]") {
  64. _id total
  65. orderGoods {
  66. good {
  67. _id
  68. name
  69. }
  70. count
  71. price
  72. total
  73. }
  74. }
  75. }`
  76. let res = await gql(query)
  77. console.log(res)
  78. return res
  79. }
  80. //получениe одного заказа по его _id
  81. let orderById = async(id) => {
  82. let query = `query orderId($id:String) {
  83. OrderFind(query:$id) {
  84. createdAt total
  85. orderGoods {
  86. good {
  87. _id
  88. name
  89. }
  90. count total price
  91. }
  92. }
  93. }`
  94. let variables = {
  95. "id": JSON.stringify([{ "_id": id }])
  96. }
  97. let res = await gql(query, variables)
  98. console.log(res)
  99. return res
  100. }