Explorar o código

upload made, additional request not function YET.

miskson %!s(int64=3) %!d(string=hai) anos
pai
achega
8fa08fc05d
Modificáronse 1 ficheiros con 60 adicións e 19 borrados
  1. 60 19
      hw22-dropzone-uploads/src/App.js

+ 60 - 19
hw22-dropzone-uploads/src/App.js

@@ -58,12 +58,12 @@ function jwtDecode(token) {
 }
 
 
-const actionLoadFile = (file) => {
-  let fd = new FormData
-  fd.append('photo', file)
+const actionLoadFile = (file, type) => {
+  let fd = new FormData()
+  fd.append(type, file)
 
   return (
-    actionPromise('loadFile', fetch(backendURL + '/upload',{
+    actionPromise('loadFile', fetch(backendURL + `/${type}`,{
       method: "POST",
       headers: localStorage.authToken ? {Authorization: 'Bearer ' + localStorage.authToken} : {},
       body: fd
@@ -88,9 +88,10 @@ const actionAboutMe = () => {
 
 const actionSetAvatar = (file) =>
   async (dispatch, getState) => {
-    await dispatch(actionLoadFile(file))
+    await dispatch(actionLoadFile(file, 'upload'))
     let picId = getState().promise?.loadFile?.payload?._id
     let userId = jwtDecode(localStorage.authToken).sub.id
+
     await dispatch(actionPromise('setAvatar', gql(`
       mutation {
         UserUpsert(user:{_id: "${userId}", avatar: {_id: "${picId}"}}){
@@ -103,23 +104,44 @@ const actionSetAvatar = (file) =>
     dispatch(actionAboutMe())
   }
 
+const actionGetUserTracks = () => {
+ //let _id = '5fe35e1ce926687ee86b0a3f' //newUserId
+  let _id = jwtDecode(localStorage.authToken).sub.id
+  return(
+      actionPromise('userTracks', gql(`
+          query getUserTracks($ownerId: String!) {
+              TrackFind(query: $ownerId) {
+                  _id, originalFileName, url,
+                  id3 { title, artist, album }
+              }
+          }
+      `, { ownerId: JSON.stringify([{ ___owner: _id }]) } ))
+  )
+}
+
+const actionAddTrack = file =>
+  async (dispatch, getState) => {
+    await dispatch(actionLoadFile(file, 'track'))
+    let trackId = getState().promise?.loadFile?.payload?._id
+    let playlistId = "61e3506ac2305e2f502aca03"
+    await dispatch(actionPromise('trackToPlaylist', gql(`
+      mutation {
+        PlaylistUpsert(playlist:{ _id: ${playlistId}, tracks: {_id: ${trackId} } }) {
+          _id, name, tracks { _id, originalFileName }
+        }
+      }
+    `)))
+    dispatch(actionGetUserTracks())
+  }
+
 function promiseReducer(state={}, {type, name, status, payload, error}){
   if (type === 'PROMISE'){
-      return {
-          ...state,
-          [name]:{status, payload, error}
-      }
+      return { ...state, [name]:{status, payload, error} }
   }
   return state
 }
 
-const store = createStore(
-  combineReducers(
-    {
-      promise: promiseReducer,
-    }
-  ), applyMiddleware(thunk)
-)
+const store = createStore(combineReducers({ promise: promiseReducer }), applyMiddleware(thunk))
 store.subscribe(() => console.log(store.getState()))
 
 function MyDropzone({uploadAvatar, userData, onLoad}) {
@@ -129,24 +151,43 @@ function MyDropzone({uploadAvatar, userData, onLoad}) {
   const {getRootProps, getInputProps, isDragActive} = useDropzone({onDrop})
 
   return (
-    <div {...getRootProps()}>
+    <div {...getRootProps()} style={{backgroundColor:'mediumseagreen'}}>
       <input {...getInputProps()} />
       {
         isDragActive ?
           <p>Drop the files here ...</p> :
-          <p>Drag 'n' drop some files here, or click to select files</p>
+          <p>Drag 'n' drop some IMAGE here, or click to select files</p>
       }
     </div>
   )
 }
-
 const ConnectDropzone = connect(null, {uploadAvatar: actionSetAvatar, onLoad: actionLoadFile, userData: actionAboutMe})(MyDropzone)
 
+function TrackDropzone({uploadTrack, userData, onLoad}) {
+  const onDrop = useCallback(acceptedFiles => {
+    uploadTrack(acceptedFiles[0])
+  }, [])
+  const {getRootProps, getInputProps, isDragActive} = useDropzone({onDrop})
+
+  return (
+    <div {...getRootProps()} style={{backgroundColor:'mediumvioletred'}}>
+      <input {...getInputProps()} />
+      {
+        isDragActive ?
+          <p>Drop the files here ...</p> :
+          <p>Drag 'n' drop some TRACK here, or click to select files</p>
+      }
+    </div>
+  )
+}
+const ConnectTrackDropzone = connect(null, {uploadTrack: actionAddTrack, onLoad: actionLoadFile, userData: actionAboutMe})(TrackDropzone)
+
 function App() {
   return (
     <Provider store={store}>
       <div className="App">
         <ConnectDropzone />
+        <ConnectTrackDropzone />
       </div>
     </Provider>
   );