index.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. const getGQL = url =>
  2. (query, variables={}) => fetch(url, {
  3. method: 'POST',
  4. headers: {
  5. "Content-Type": "application/json",
  6. ...(localStorage.authToken ? {Authorization: "Bearer " + localStorage.authToken } : {})
  7. },
  8. body: JSON.stringify({query, variables})
  9. }).then(res => res.json())
  10. export const actionPending = name => ({type: 'PROMISE', status: 'PENDING', name})
  11. export const actionResolved = (name, payload) => ({type: 'PROMISE', status: 'RESOLVED', name, payload})
  12. export const actionRejected = (name, error) => ({type: 'PROMISE', status: 'REJECTED', name, error})
  13. let shopGQL = getGQL('/graphql')
  14. export const actionPromise = (name, promise) =>
  15. async dispatch => {
  16. dispatch(actionPending(name))
  17. try{
  18. let payload = await promise
  19. dispatch(actionResolved(name, payload))
  20. return payload
  21. }
  22. catch(error){
  23. dispatch(actionRejected(name, error))
  24. }
  25. }
  26. const actionAuthLogin = token => ({type:'LOGIN', token})
  27. export const actionAuthLogout = () => ({type:"LOGOUT"})
  28. let log = async (login, password) => {
  29. let query = `query log($l: String!, $p: String!) {
  30. login(login: $l, password: $p)
  31. }`
  32. let variables = {
  33. "l": login,
  34. "p": password
  35. }
  36. let token = await shopGQL(query, variables)
  37. console.log(token)
  38. return token.data.login
  39. }
  40. const actionLogin = (login, password) => actionPromise("login", log(login, password))
  41. export const actionFullLogin = (login, password) => {
  42. return async (dispatch) => {
  43. let result = await dispatch(actionLogin(login, password))
  44. if(result) {
  45. dispatch(actionAuthLogin(result))
  46. dispatch(actionUserInfo())
  47. }
  48. }
  49. }
  50. const actionRegister = (login,password) =>
  51. actionPromise('reg',shopGQL(`mutation reg($login: String!, $password: String!){
  52. createUser(login:$login, password: $password){
  53. _id login
  54. }
  55. }`,{login,password}))
  56. export const actionFullRegister = (login,password) =>
  57. async dispatch => {
  58. let payload = await dispatch(actionRegister(login,password))
  59. if(payload.data.createUser != null){
  60. await dispatch(actionFullLogin(login,password))
  61. }
  62. else {
  63. console.log("exiciting user")
  64. }
  65. }
  66. export const actionTypeAd = (_id,title) =>
  67. actionPromise('AdFind', shopGQL(`
  68. query Ad($query:String){
  69. AdFind(query:$query){
  70. _id
  71. title
  72. description
  73. price
  74. images {
  75. url
  76. }
  77. comments {
  78. _id text owner {login} answerTo { owner { login}}
  79. }
  80. createdAt
  81. owner {login}
  82. }
  83. }
  84. `, {query: JSON.stringify([{field: title},{sort: [{_id: -1}]}])}))
  85. export const actionTypeAdOne = (id) =>
  86. actionPromise('AdFindOne',shopGQL(`
  87. query Ad($query:String){
  88. AdFindOne(query:$query){
  89. _id
  90. title
  91. description
  92. price
  93. images {
  94. url
  95. }
  96. comments {
  97. _id text owner {login} answerTo { text owner{ login}}
  98. }
  99. createdAt
  100. owner {login , createdAt}
  101. }
  102. }`,{query: JSON.stringify([{_id:id}])}))
  103. // export const actionComments = (ad) =>
  104. // actionPromise('Comments',shopGQL(`
  105. // query Comments($query: String){
  106. // CommentFind(query: $query){
  107. // _id
  108. // text
  109. // owner {login}
  110. // ad {_id}
  111. // answerTo {text owner{login}}
  112. // }
  113. // }`,{query: JSON.stringify([{}])}))
  114. export const actionPostAd = (title,description,price,_id) =>
  115. actionPromise('PostAd',shopGQL(`
  116. mutation Post($ad: AdInput){
  117. AdUpsert(ad: $ad) {
  118. _id
  119. title
  120. description
  121. price
  122. images {
  123. url
  124. }
  125. }
  126. }`,{ad: {title,description,price,_id}}))
  127. export const actionMyPosts = () =>
  128. async (dispatch,getState) => {
  129. let userId = getState().authReducer.payload.sub.id
  130. return await dispatch(actionPromise('MyPosts',shopGQL(`
  131. query MyPosts($query: String){
  132. AdFind(query: $query){
  133. _id
  134. title
  135. description
  136. price
  137. images {
  138. url
  139. }
  140. comments {
  141. _id text owner {login} answerTo { owner { login}}
  142. }
  143. }
  144. }`,{query: JSON.stringify([{___owner: userId}])})))
  145. }
  146. // export const actionCommentAdd = () =>
  147. // actionPromise('CommentAdd',shopGQL(`
  148. // mutation Comment($comment : CommentInput){
  149. // CommentUpsert(comment: $comment) {
  150. // _id
  151. // ad
  152. // text
  153. // }
  154. // }`,{comment:{text,answerTo,ad:{_id}}}))
  155. export const actionUploadFile = (file) => {
  156. let fd = new FormData
  157. fd.append('photo', file)
  158. return actionPromise('photo',fetch('/upload', {
  159. method: "POST",
  160. headers: localStorage.authToken ? {Authorization: 'Bearer ' + localStorage.authToken} : {},
  161. body: fd
  162. }).then(res => res.json()))
  163. };
  164. const actionAvaAdd = (avaId) =>
  165. async (dispatch,getState) => {
  166. let userId = getState().authReducer.payload.sub.id
  167. await dispatch (actionPromise('ava',shopGQL(`mutation setAvatar($userId: String, $avaId: ID){
  168. UserUpsert(user:{_id: $userId, avatar: {_id: $avaId}}){
  169. _id, avatar{
  170. _id
  171. }
  172. }
  173. }`,{avaId,userId})))
  174. }
  175. export const actionAvaChange = (file) =>
  176. async (dispatch) => {
  177. let res = await dispatch(actionUploadFile(file))
  178. if(res) {
  179. await dispatch(actionAvaAdd(res._id))
  180. await dispatch(actionUserInfo())
  181. }
  182. }
  183. export const actionUserInfo = () =>
  184. async (dispatch,getState) => {
  185. let userId = getState().authReducer.payload.sub.id
  186. await dispatch(actionPromise('UserInfo',shopGQL(`
  187. query UserInfo($query:String){
  188. UserFindOne(query: $query){
  189. _id login avatar {url}
  190. }
  191. }`,{query: JSON.stringify([{_id: userId}])})))
  192. }
  193. const regexp = (string) => `/${string.split([" "]).join(['|']).trim()}/`
  194. const toQuery = (queryString, fields = ["title", "description"]) => ({ $or: fields.map(string => ({ [string]: regexp(queryString) }))})
  195. export const actionSearch = (queryString) =>
  196. async (dispatch) =>
  197. await dispatch(actionPromise('SearchAd',shopGQL(`
  198. query AdFind($query: String){
  199. AdFind(query: $query) {
  200. _id
  201. title
  202. description
  203. price
  204. images {
  205. url
  206. }
  207. }
  208. }`,{query: JSON.stringify([toQuery(queryString),
  209. {
  210. sort: [{_id: -1}],
  211. limit: [15]
  212. }]
  213. )}
  214. )
  215. ))
  216. // const toRegexp2 = queryString => `/${queryString.split([" "]).join(['|']).trim()}/`
  217. // const toQuery = (queryString, fields = ["id3.artist", "id3.title", "id3.album"]) => ({ $or: fields.map(x => ({ [x]: toRegexp2(queryString) })) })
  218. // const actionSearch = (queryString) =>
  219. // async dispatch => {
  220. // let searchData = await dispatch(actionPromise('search', gql(
  221. // `query trackFind($query: String) {
  222. // TrackFind(query:$query)
  223. // {
  224. // originalFileName
  225. // url
  226. // id3 {
  227. // title
  228. // artist
  229. // album
  230. // }
  231. // }
  232. // }`, {
  233. // query: JSON.stringify([toQuery(queryString),
  234. // {
  235. // sort: [{ _id: -1 }], //сортировка в обратном хронологическом порядке
  236. // limit: [10], //100 записей максимум
  237. // }])
  238. // }
  239. // )))
  240. // console.log(searchData)
  241. // }