script.js 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. function createStore(reducer){
  2. let state = reducer(undefined, {})
  3. let cbs = []
  4. const getState = () => state
  5. const subscribe = cb => (cbs.push(cb),
  6. () => cbs = cbs.filter(c => c !== cb))
  7. const dispatch = action => {
  8. if (typeof action === 'function'){
  9. return action(dispatch, getState)
  10. }
  11. const newState = reducer(state, action)
  12. if (newState !== state){
  13. state = newState
  14. for (let cb of cbs) cb()
  15. }
  16. }
  17. return {
  18. getState,
  19. dispatch,
  20. subscribe
  21. }
  22. }
  23. const getGQL = url =>
  24. (query, variables) => fetch(url, {
  25. method: 'POST',
  26. headers: {
  27. "Content-Type": "application/json",
  28. // 'Accept' : 'application/json',
  29. ...(localStorage.authToken ? {"Authorization": "Bearer " + localStorage.authToken} : {})
  30. },
  31. body: JSON.stringify({query, variables})
  32. }).then(res => res.json())
  33. .then(data => {
  34. if (data.data){
  35. return Object.values(data.data)[0]
  36. }
  37. else throw new Error(JSON.stringify(data.errors))
  38. })
  39. const backendURL = 'http://shop-roles.asmer.fs.a-level.com.ua'
  40. const gql = getGQL(backendURL + '/graphql');
  41. function promiseReducer(state={}, {type, name, status, payload, error}){
  42. if (type === 'PROMISE'){
  43. return {
  44. ...state,
  45. [name]:{status, payload, error}
  46. }
  47. }
  48. return state
  49. }
  50. const actionPending = name => ({type:'PROMISE',name, status: 'PENDING'})
  51. const actionFulfilled = (name,payload) => ({type:'PROMISE',name, status: 'FULFILLED', payload})
  52. const actionRejected = (name,error) => ({type:'PROMISE',name, status: 'REJECTED', error})
  53. const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
  54. const store = createStore(promiseReducer);
  55. store.subscribe(() => console.log(store.getState()))
  56. //store.dispatch(actionPending('delay1000'))
  57. ////{ 1
  58. //// delay1000: {status: 'PENDING'}
  59. ////}
  60. //delay(1000).then(result => store.dispatch(actionFulfilled('delay1000', result)))
  61. ////{ 3
  62. //// delay1000: {status: 'FULFILLED', payload: 1000},
  63. //// delay2000: {status: 'PENDING'}
  64. ////}
  65. //store.dispatch(actionPending('delay2000'))
  66. ////{ 2
  67. //// delay1000: {status: 'PENDING'},
  68. //// delay2000: {status: 'PENDING'}
  69. ////}
  70. //delay(2000).then(result => store.dispatch(actionFulfilled('delay2000', result)))
  71. ////{ 4
  72. //// delay1000: {status: 'FULFILLED', payload: 1000},
  73. //// delay2000: {status: 'FULFILLED', payload: 2000}
  74. ////}
  75. const actionPromise = (name, promise) =>
  76. async dispatch => {
  77. dispatch(actionPending(name))
  78. try {
  79. let payload = await promise
  80. dispatch(actionFulfilled(name, payload))
  81. return payload
  82. }
  83. catch(error){
  84. dispatch(actionRejected(name, error))
  85. }
  86. }
  87. store.dispatch(actionPromise('delay1000', delay(1000)))
  88. store.dispatch(actionPromise('delay2000', delay(2000)))
  89. const actionLuke = () => actionPromise('luke',
  90. fetch('https://swapi.dev/api/people/1')
  91. .then(res => res.json()))
  92. store.dispatch(actionLuke())
  93. const actionRegister = (login, password) =>
  94. actionPromise('register', gql( `mutation register($login: String, $password: String) {
  95. UserUpsert(user: {login: $login, password: $password}) {
  96. _id
  97. login
  98. }
  99. }`, {login : login, password : password}))
  100. store.dispatch(actionRegister('user777', '777'));
  101. const actionCategoryById = (_id) =>
  102. actionPromise('catById', gql(`query catById($q: String){
  103. CategoryFindOne(query: $q){
  104. _id name goods {
  105. _id name price images {
  106. url
  107. }
  108. }
  109. }
  110. }`, {q: JSON.stringify([{_id}])}));
  111. store.dispatch(actionCategoryById("5dc458985df9d670df48cc47"));
  112. const actionGoodById = (_id) =>
  113. actionPromise('goodById', gql(`query goodByid($goodId: String) {
  114. GoodFindOne(query: $goodId) {
  115. name
  116. price
  117. description
  118. images {
  119. url
  120. }
  121. }
  122. }`, {goodId: JSON.stringify([{_id}])}))
  123. store.dispatch(actionGoodById("5dc4a3e15df9d670df48cc6b"));
  124. const actionRootCategories = () =>
  125. actionPromise('rootCats', gql(`query {
  126. CategoryFind(query: "[{\\"parent\\":null}]"){
  127. _id name
  128. }
  129. }`))
  130. store.dispatch(actionRootCategories());
  131. const actionNewOrder = (order) =>
  132. actionPromise('newOrder', gql( `mutation newOrder($order: OrderInput) {
  133. OrderUpsert(order: $order) {
  134. _id
  135. total
  136. }
  137. }`, {order : order}
  138. )
  139. )
  140. let order = {
  141. orderGoods: [
  142. {count: 2, good: {_id: "5dcac57d6d09c45440d14cfc"}},
  143. {count: 2, good: {_id: "5dcac9ba6d09c45440d14d02"}},
  144. {count: 1, good: {_id: "5dc8844e0e36db246e3049bd"}},
  145. ]
  146. }
  147. store.dispatch(actionNewOrder(order));
  148. const actionOrders = () =>
  149. actionPromise('allOrders', gql(`query findOrder($q: String) {
  150. OrderFind(query: $q) {
  151. _id
  152. total
  153. orderGoods {
  154. count
  155. good {
  156. name
  157. price
  158. }
  159. }
  160. }
  161. }`, {q: JSON.stringify([{}])}))
  162. store.dispatch(actionOrders())