index.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. // // получение объекта из jwt токена
  2. // const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOnsiaWQiOiI2MWE0ZGIyOWM3NTBjMTJiYTZiYTQwMjIiLCJsb2dpbiI6ImVxd2VxZXdldyIsImFjbCI6WyI2MWE0ZGIyOWM3NTBjMTJiYTZiYTQwMjIiLCJ1c2VyIl19LCJpYXQiOjE2MzgxOTQ1NzZ9.Pi1GO6x7wdNrIrUKCQT-32-SsqmgFY-oFDrrXmw74-8'
  3. // JSON.parse(atob(token.split('.')[1]))
  4. // // получение контрольных сумм
  5. // let qqq = 'fdhfakfalfjskgfsdadasdasdasdasdadfsdfkarieqfowerdaesfa'
  6. // function checkSum(str) {
  7. // let res = 0
  8. // for (let letter of str) {
  9. // res += letter.charCodeAt()
  10. // }
  11. // return res
  12. // }
  13. // console.log(checkSum(qqq))
  14. // // добавление соли (секретная последовательность) к информации
  15. // // для формирования уникальной контрольной суммы
  16. // function sign(data, salt) {
  17. // const json = JSON.stringify(data)
  18. // const sum = checkSum(json + salt)
  19. // return json + sum
  20. // }
  21. // function verify(signed, salt) {
  22. // const json = signed.slice(0, signed.lastIndexOf('}') + 1)
  23. // const tokenSum = + signed.slice(signed.lastIndexOf('}') + 1)
  24. // const sum = checkSum(json + salt)
  25. // console.log(json, tokenSum, sum)
  26. // return sum === tokenSum
  27. // }
  28. // добавить заголовок Authorization если в localStorage есть authToken (не забудьте слово Bearer и пробел после него.
  29. // Таким образом все запросы будут уходить не анонимно если в localStorage есть токен.
  30. const getGQL = (url) => (
  31. (query, variables) => fetch(url, {
  32. method: 'POST',
  33. headers: {
  34. "Content-Type": "application/json",
  35. ...(localStorage.authToken ? {Authorization: "Bearer " + localStorage.authToken} : {})
  36. },
  37. body: JSON.stringify({query, variables})
  38. }).then(res => res.json()).then(async (data) => {
  39. if ('errors' in data) {
  40. // return Promise.reject(new Error('ОШИБКА'))
  41. throw new Error('ОШИБКА!!!!' + JSON.stringify(data.errors))
  42. } else {
  43. return data.data[Object.keys(data.data)[0]]
  44. }
  45. })
  46. );
  47. const gql = getGQL('http://shop-roles.asmer.fs.a-level.com.ua/graphql');
  48. // написать функции по типу:
  49. // для логина, регистрации, а так же для остальных страниц будущего сайта, которые вам пришли на ум.
  50. function login(log, pass) {
  51. return gql(`query log($login: String, $password: String) {
  52. login(login: $login, password: $password)
  53. }
  54. `, {login: log, password: pass})
  55. }
  56. function register(log, pass) {
  57. return gql(`mutation reg2($user:UserInput) {
  58. UserUpsert(user:$user) {
  59. _id login
  60. }
  61. }
  62. `, {user: {login: log, password: pass}})
  63. }
  64. function findUsers(_id = '') {
  65. return gql(`query userFind {
  66. UserFind(query: "[{}]") {
  67. login
  68. nick
  69. _id
  70. }
  71. }
  72. `, {query: JSON.stringify([{_id}])})
  73. }
  74. function catById(_id) {
  75. return gql(`query catById($query:String) {
  76. CategoryFindOne(query:$query) {
  77. name goods{
  78. _id name images{
  79. url
  80. }
  81. }
  82. subCategories {
  83. _id name
  84. }
  85. }
  86. }`, {query: JSON.stringify([{_id}])})
  87. }
  88. function cats() {
  89. return gql(`query cats($query: String) {
  90. CategoryFind(query: $query) {
  91. _id name
  92. goods {
  93. name
  94. images {
  95. url
  96. }
  97. }
  98. }
  99. }`, {query: JSON.stringify([{}])})
  100. }
  101. function goodById(_id) {
  102. return gql(`query goodById($q: String) {
  103. GoodFindOne(query: $q) {
  104. _id name price description images {
  105. url
  106. }
  107. }
  108. }`, {q: JSON.stringify([{_id}])})
  109. }
  110. function orders() {
  111. return gql(`query o($query: String) {
  112. OrderFind(query:$query){
  113. _id orderGoods{
  114. price count total good{
  115. name categories{
  116. name
  117. }
  118. }
  119. }
  120. owner {
  121. _id login
  122. }
  123. }
  124. }`, {query: JSON.stringify([{}])})
  125. }
  126. // function ordersByUserId(_id) {
  127. // return gql(`query oUser($query: String) {
  128. // OrderFind(query:$query){
  129. // _id orderGoods{
  130. // price count total good{
  131. // name categories{
  132. // name
  133. // }
  134. // }
  135. // }
  136. // owner {
  137. // _id login
  138. // }
  139. // }
  140. // }`,
  141. // {query: JSON.stringify([
  142. // {owner: {_id}}
  143. // ])})
  144. // }
  145. function newOrder(_id, count) {
  146. return gql(`mutation newOrder($q: OrderInput){
  147. OrderUpsert(order: $q)
  148. {
  149. _id total
  150. }
  151. }`, {q: {
  152. orderGoods:[
  153. {count, good:{_id}},
  154. // {count: count, good:{_id}}
  155. ]
  156. }})
  157. }
  158. ;
  159. (async function() {
  160. let allUsers = await findUsers()
  161. console.log(allUsers)
  162. let token1 = await login('tst', '123')
  163. console.log(token1)
  164. if (typeof jwtDecode(token1) === 'object') {
  165. localStorage.authToken = token1
  166. }
  167. // console.log(await register('zzaa', 'zzaa'))
  168. let cat = await catById("5dc45acf5df9d670df48cc48")
  169. console.log(cat)
  170. let allCats = await cats()
  171. console.log(allCats)
  172. let good = await goodById('5dcad3606d09c45440d14d10')
  173. console.log(good)
  174. let ord = await orders()
  175. console.log(ord)
  176. let newOrd = await newOrder('5dcad3606d09c45440d14d10', 5)
  177. console.log(newOrd)
  178. })();
  179. function jwtDecode(token) {
  180. try {
  181. let decoded = JSON.parse(atob(token.split('.')[1]))
  182. return decoded
  183. } catch (err) {
  184. console.log(err)
  185. }
  186. }