Explorar el Código

Add actionPostsFeed + finish correct uploadFiles

LenDoc hace 2 años
padre
commit
d2d767e5a9
Se han modificado 5 ficheros con 85 adiciones y 80 borrados
  1. 59 24
      src/App.js
  2. 17 33
      src/actions/index.js
  3. 2 2
      src/components/DropZone.js
  4. 4 18
      src/components/NewPost.js
  5. 3 3
      src/components/User.js

+ 59 - 24
src/App.js

@@ -38,20 +38,25 @@ import { LeftCircleFilled, RightCircleFilled } from '@ant-design/icons'
 import { Input,Select } from 'antd';
 console.log(store.getState())
 store.subscribe(() => console.log(store.getState()))
+// 
+console.log('ABOUT ME',store.getState().auth?.payload?.sub?.id);
+// console.log('ABOUT FOLLOWING',store.getState().promise.aboutUser?.payload?.following);
+//store.dispatch(actionPostsFeed())
 
-console.log('ABOUT ME',store.getState().auth?.payload?.sub?._id);
 const PageMain = () => <div className="PageMain">ГЛАВНАЯ</div>
 
 
 const PageFeed = ({ aboutMe,allFollowing, onPostsFeed, onAllFollowing}) => {
+  console.log('ABOUT FOLLOWING',store.getState().promise.aboutMe?.payload?.following);
 // const Following =[]
   useEffect(() => {
-    onAllFollowing(aboutMe?._id)
+    onPostsFeed()
   }, [])
-  useEffect(() => {
-     onPostsFeed(allFollowing?.following?.map(({_id})=>(_id)))
-  }, [])
-  console.log('allFollowing',allFollowing?.following?.map(({_id})=>(_id)))
+  // useEffect(() => {
+  //    onPostsFeed()
+  // store.dispatch(actionPostsFeed())
+  // console.log('allFollowing',allFollowing?.following?.map(({_id})=>(_id)))
+  // console.log('onPost', store.dispatch(actionPostsFeed))
 
   return <>
  <div style={{background: '#FFFACD' }}>
@@ -60,14 +65,15 @@ const PageFeed = ({ aboutMe,allFollowing, onPostsFeed, onAllFollowing}) => {
   </div>
    </>
 }
-const CPageFeed =connect((state)=>({
-  aboutMe: state.promise.aboutMe?.payload , 
-   allFollowing: state.promise?.allFollowing?.payload,
+const CPageFeed =connect((state)=>(
+  {
+  
+    aboutMe: state.promise.aboutMe?.payload , 
+  //  allFollowing: state.promise?.allFollowing?.payload,
    allPosts: state.promise?.allPosts?.payload,
    postsFeed: state.promise?.postsFeed?.payload,
-   followingPosts: state.promise?.followingPosts?.payload
-  }), {onPostsFeed:actionPostsFeed,
-      onAllFollowing:actionAllFollowing})(PageFeed)
+  //  followingPosts: state.promise?.followingPosts?.payload
+  }), {onPostsFeed:actionPostsFeed})(PageFeed)
 const Main = () => (
   <main>
     <Switch>
@@ -113,8 +119,16 @@ return <>
 </>
 }
 const CSearch = connect((state)=>({searchUser:state.promise?.searchUser?.payload}), {onSearch:actionSearchUser})(SearchUser)
-const Header = () => {
+const Feed = ({aboutMe,onAllFollowing, onPostsFeed, postsFeed}) => {
+console.log('POST FEED', postsFeed)
+return <> 
+<Link className="Feed" to={`/feed`}>
 
+<Button className="Feed" onClick={()=>console.log('click')}> Feed </Button>
+</Link>
+</>}
+const Header = () => {
+  const CFeed =connect((state) => ({aboutMe: state.promise?.aboutMe?.payload}))(Feed)
  return  <section className="Header">
     <CSearch/>
     {/* <Button icon={<SearchOutlined />}>Search</Button> */}
@@ -126,15 +140,7 @@ const Header = () => {
   </section>
 }
 const Likes = () => <Button className="Likes"> Likes </Button>
-const Feed = ({aboutMe,onAllFollowing}) => 
-<>
-
-<Link className="Feed" to={`/feed`}>
 
-<Button className="Feed" onClick={()=>onAllFollowing(aboutMe?._id)}> Feed </Button>
-</Link>
-</>
-const CFeed =connect((state) => ({aboutMe: state.promise?.aboutMe?.payload}),{onAllFollowing:actionAllFollowing})(Feed)
 const Recommendations = () => (
   <Button className="Recomendations"> Recommendations </Button>
 )
@@ -151,13 +157,40 @@ const User = ({ aboutMe: { _id, login, avatar } = {} }) => (
 const CUser = connect((state) => ({ aboutMe: state.promise.aboutMe?.payload }))(
   User
 )
+  
+//  store.getState().auth?.payload?.sub?.id
+
+
+const ProtectedRoute = ({roles=[], fallback='/login', component, auth, ...routeProps})=>{
+  console.log('LFLFLFL')
+  const WrapperComponent = (renderProps)=>{
+    // console.log('тут шото ', intersection)
+    const C = component;
+   if (!auth)
+    auth=["anon"]
+
+    let intersection = auth.filter(x => roles.includes(x));
+   if (intersection.length==0)
+    return <Redirect  to={fallback} />
+
+    return <C {...renderProps}/>
+  }
+  return <Route {...routeProps} component ={WrapperComponent}/>
+}
+const PageRegister = ()=>{
+return <div>
+  REGISTER
+</div>}
+const CProtectedRoute = connect(state=>({auth:state.auth?.payload?.sub.acl}))(ProtectedRoute);
+
 
+ 
 const history = createHistory()
 function App() {
-  if (store.getState().auth?.token &&store.getState().auth?.payload?.sub?._id)
- store.dispatch(actionAboutMe(store.getState().auth?.payload?.sub?._id))
- 
+    if (store.getState().auth?.token)
+    store.dispatch(actionAboutMe(store.getState().auth?.payload?.sub?.id))
   return (
+
     <Router history={history}>
       <Provider store={store}>
         
@@ -165,6 +198,8 @@ function App() {
           <Header />
           <Divider />
           <Main />
+          <CProtectedRoute roles={["anon"]} fallback="/dashboard"
+           path="/register" component={PageRegister}/>
           {/* <CPostEditor /> */}
           {/* <CPost /> */}
           {/* <Gallery/> */}

+ 17 - 33
src/actions/index.js

@@ -104,7 +104,7 @@ export const actionUploadFile = (file) =>
 export const actionUploadFiles = (files) =>
   actionPromise(
     'uploadFiles',
-    Promise.all(files?.map((file) => uploadFile(file))),
+    Promise.all(files.map((file) => uploadFile(file))),
   )
 const actionAvatar = (imageId) => async (dispatch, getState) => {
   await dispatch(
@@ -123,10 +123,10 @@ const actionAvatar = (imageId) => async (dispatch, getState) => {
     ),
   )
 }
-export const actionAboutMe = (id) => async (dispatch, getState) => {
+export const actionAboutMe = () => async (dispatch, getState) => {
   await dispatch(
     actionPromise(
-      'aboutMe',
+    'aboutMe',
       gql(
         `query AboutMe($userId:String){
   UserFindOne(query:$userId)
@@ -136,32 +136,14 @@ export const actionAboutMe = (id) => async (dispatch, getState) => {
   }
 }`,
         {
-          userId: JSON.stringify([{ _id:id }]),
+          userId: JSON.stringify([{ _id: getState().auth?.payload?.sub?.id }]),
         },
       ),
     ),
   )
 }
-export const actionAboutUser = (_id) => async (dispatch, getState) => {
-  await dispatch(
-    actionPromise(
-      'aboutUser',
-      gql(
-        `query AboutUser($userId:String){
-  UserFindOne(query:$userId)
-    {
-      _id createdAt login nick avatar{_id url} 
-      followers{_id login nick} following{_id login nick}
-    }
-}`,
-        {
-          userId: JSON.stringify([{ _id: _id }]),
-        },
-      ),
-    ),
-  )
-}
-
+// export const actionAboutUser = actionAboutMe
+// :'aboutMe'
 export const actionPostUpsert = (post) =>
   actionPromise(
     'postUpsert',
@@ -208,8 +190,8 @@ export const actionOnePost = (_id) => async (dispatch) => {
       'onePost',
       gql(
         `query OneFind($post:String){
-  PostFindOne(query:$post){
-           _id title text images{_id url}
+         PostFindOne(query:$post){
+        _id title text images{_id url}
     }
 }`,
         {
@@ -265,8 +247,9 @@ export const actionSetAvatar = (file) => async (dispatch) => {
     await dispatch(actionAboutMe())
   }
 }
-
-export const actionPostsFeed = (Following) => async (dispatch) => {
+// let following =  getState().promise.aboutUser?.payload?.following  
+// let result =  await dispatch (actionAboutMe())
+export const actionPostsFeed = () => async (dispatch,getState) => {
   await dispatch(
     actionPromise(
       'postsFeed',
@@ -283,12 +266,13 @@ export const actionPostsFeed = (Following) => async (dispatch) => {
       	}
     }`,
         {
-          ownerId: JSON.stringify([
-            { ___owner: {$in: Following}},
+            ownerId: JSON.stringify([
+            { ___owner: {$in:  
+              getState().promise.aboutMe?.payload?.following.map(({ _id }) => (_id))}},
             {
-              sort: [{ _id: -1 }], //сортировка в обратном хронологическом порядке
-              skip: [0], //отступаем 1000 записей
-               limit: [10], //100 записей максимум
+              sort: [{ _id: -1 }],
+              skip: [0],
+               limit: [30],
             },
           ]),
         },

+ 2 - 2
src/components/DropZone.js

@@ -15,8 +15,8 @@ export function Basic({ onLoad }) {
     ))
     console.log('acceptedFiles',acceptedFiles)
     useEffect(() => {
-      if(acceptedFiles[0])
-        onLoad(acceptedFiles[0])
+      if(acceptedFiles)
+        onLoad(acceptedFiles)
     }
     , [acceptedFiles])
     return (

+ 4 - 18
src/components/NewPost.js

@@ -55,15 +55,7 @@ export const AddPost = ({ children }) => {
     />
   )
 const PostEditor = ({ post = defaultPost, onSave, onFileDrop, fileStatus }) => {
-    //по файлу в дропзоне:
-    //дергать onFileDrop
-    //fileStatus - информация о заливке файла из redux
-    //через useEffect дождаться когда файл зальется
-    // console.log('_id ', uploadFiles?.payload?.images?._id)
-    // console.log('url  ', uploadFiles?.payload?.images?.url)
-  
-    console.log('ON FILE DROP ', onFileDrop)
-  
+    console.log('filestatus ', fileStatus)
     const [state, setState] = useState(post)
     useEffect(() => {
       fileStatus?.status == 'FULFILLED' &&
@@ -71,15 +63,9 @@ const PostEditor = ({ post = defaultPost, onSave, onFileDrop, fileStatus }) => {
           ...state,
           images: [
             ...state.images,
-            {
-              
-              _id: fileStatus?.payload?._id,
-              url: fileStatus?.payload?.url,
-            },
+            ...fileStatus.payload
           ],
         })
-        &&  console.log('_id ', fileStatus?.payload?._id)&&
-        console.log('url  ', fileStatus?.payload?.url)
     }, [fileStatus])
   
     const onSortEnd = ({ oldIndex, newIndex }) => {
@@ -130,9 +116,9 @@ const PostEditor = ({ post = defaultPost, onSave, onFileDrop, fileStatus }) => {
     )
   }
  export const CPostEditor = connect(
-    (state) => ({ fileStatus: state.promise?.uploadFile}),
+    (state) => ({ fileStatus: state.promise?.uploadFiles}),
     {
       onSave: actionPostUpsert,
-      onFileDrop: actionUploadFile,
+      onFileDrop: actionUploadFiles,
     },
   )(PostEditor)

+ 3 - 3
src/components/User.js

@@ -7,14 +7,14 @@ import { Avatar, Image, Divider, Radio } from 'antd'
 import { store } from '../reducers'
 
 const PageAboutUser = ({
-    aboutMe: { _id, login, nick, createdAt, avatar, followers, following } = {},
+  aboutMe: { _id, login, nick, createdAt, avatar, followers, following } = {},
     allPosts,
     onPosts,
     onPost,
     onAboutUser
   }) => {
     useEffect(() => {
-      // onAboutUser(_id)
+      onAboutUser(_id)
       onPosts()
     }, [])
 
@@ -75,6 +75,6 @@ const PageAboutUser = ({
       allPosts: state.promise?.allPosts?.payload,
     }),
     { onPosts: actionAllPosts, onPost: actionOnePost,
-    // onAboutUser: actionAboutMe
+     onAboutUser: actionAboutMe
     },
   )(PageAboutUser)