Skip to content

Commit

Permalink
fix upload datafile view bug (#663)
Browse files Browse the repository at this point in the history
Co-authored-by: Aakaash Meduri <aakaash.meduri@gmail.com>
  • Loading branch information
thetechnocrat-dev and acashmoney committed Sep 26, 2023
1 parent 5e8635d commit acd9686
Show file tree
Hide file tree
Showing 8 changed files with 28 additions and 63 deletions.
39 changes: 6 additions & 33 deletions frontend/app/datafile/add/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,17 @@ import Grid from '@mui/material/Grid'
import Button from '@mui/material/Button'
import Alert from '@mui/material/Alert'
import Typography from '@mui/material/Typography'
// import { useRouter } from 'next/router'
import { useRouter } from 'next/navigation'

export default function DataFileForm() {
const dispatch = useDispatch()
// const router = useRouter()

const cid = useSelector(selectCID)
const router = useRouter()
const errorMessage = useSelector(selectDataFileError)
const isLoading = useSelector(selectDataFileIsLoading)
const walletAddress = useSelector(selectWalletAddress)

const [file, setFile] = useState<File | null>(null)
const [isPublic, setIsPublic] = useState<boolean>(true)
const [isVisible, setIsVisible] = useState<boolean>(true)

const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const uploadedFile = e.target.files && e.target.files[0]
Expand All @@ -40,12 +37,8 @@ export default function DataFileForm() {
}
}

const handlePublicChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setIsPublic(!e.target.checked)
}

const handleVisibleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setIsVisible(!e.target.checked)
const handleSuccess = () => {
router.push('/datafile/list')
}

const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
Expand All @@ -57,13 +50,11 @@ export default function DataFileForm() {

dispatch(startLoading())
dispatch(setError(null))
const metadata = { walletAddress, isPublic, isVisible };
const metadata = { walletAddress };

try {
await dispatch(saveDataFileAsync({ file, metadata }))
await dispatch(saveDataFileAsync({ file, metadata, handleSuccess }))
dispatch(endLoading())

// router.push('/data/list')
} catch (error) {
dispatch(setError("Error uploading file"))
dispatch(endLoading())
Expand All @@ -87,24 +78,6 @@ export default function DataFileForm() {
/>
</Button>
</Grid>
<Grid item container justifyContent="center">
<label>
<input
type="checkbox"
checked={!isPublic}
onChange={handlePublicChange}
/>
File should be private
</label>
<label>
<input
type="checkbox"
checked={!isVisible}
onChange={handleVisibleChange}
/>
File should be hidden
</label>
</Grid>
{errorMessage && (
<Box my={2}>
<Alert severity="error" variant="filled">
Expand Down
6 changes: 0 additions & 6 deletions frontend/app/datafile/list/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ export default function ListDataFiles() {
CID: string;
WalletAddress: string;
Filename: string;
IsPublic: boolean;
IsVisible: boolean;
}

const [datafiles, setDataFiles] = useState<DataFile[]>([]);
Expand All @@ -43,8 +41,6 @@ export default function ListDataFiles() {
<TableCell>CID</TableCell>
<TableCell>Uploader Wallet</TableCell>
<TableCell>Filename</TableCell>
<TableCell>Is Public</TableCell>
<TableCell>Is Visible</TableCell>
</TableRow>
</TableHead>
<TableBody>
Expand All @@ -57,8 +53,6 @@ export default function ListDataFiles() {
</TableCell>
<TableCell>{datafile.WalletAddress}</TableCell>
<TableCell>{datafile.Filename}</TableCell>
<TableCell>{datafile.IsPublic ? 'Yes' : 'No'}</TableCell>
<TableCell>{datafile.IsVisible ? 'Yes' : 'No'}</TableCell>
</TableRow>
))}
</TableBody>
Expand Down
2 changes: 0 additions & 2 deletions frontend/app/job/init/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ export default function InitJob() {
WalletAddress: string;
Filename: string;
Timestamp: Date;
Public: boolean;
Visible: boolean;
}

const [tools, setTools] = useState<Tool[]>([]);
Expand Down
8 changes: 3 additions & 5 deletions frontend/lib/redux/slices/dataFileAddSlice/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,16 @@ export const saveDataFileToServer = async (
const formData = new FormData();
formData.append('file', file, file.name);
formData.append('filename', file.name)
formData.append('isPublic', String(metadata.isPublic))
formData.append('isVisible', String(metadata.isVisible))

for (const key in metadata) {
formData.append(key, metadata[key]);
}

const response = await fetch(`${backendUrl()}/add-datafile`, {
method: 'POST',
body: formData,
})

if (!response.ok) {
let errorMsg = 'An error occurred while uploading the data file'
try {
Expand All @@ -30,7 +28,7 @@ export const saveDataFileToServer = async (
console.log('errorMsg', errorMsg)
throw new Error(errorMsg)
}

const result = await response.json()
console.log('result', result)
return result;
Expand Down
7 changes: 4 additions & 3 deletions frontend/lib/redux/slices/dataFileAddSlice/thunks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,17 @@ import { setCidDataSlice, setFilenameDataSlice, setDataFileError } from './dataS
interface DataFilePayload {
file: File,
metadata: { [key: string]: any }
handleSuccess: () => void
}

export const saveDataFileAsync = createAppAsyncThunk(
'dataFile/saveDataFile',
async ({ file, metadata }: DataFilePayload, { dispatch }) => {
async ({ file, metadata, handleSuccess }: DataFilePayload, { dispatch }) => {
try {
const response = await saveDataFileToServer(file, metadata);
console.log("Response:", response)
if (response.filename) {
dispatch(setFilenameDataSlice(response.filename));
if (response.cid) {
handleSuccess()
} else {
dispatch(setDataFileError('Failed to save data file.'))
}
Expand Down
16 changes: 6 additions & 10 deletions gateway/handlers/datafiles.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@ import (
"github.com/labdao/plex/gateway/utils"
"github.com/labdao/plex/internal/ipfs"

"log"

"gorm.io/gorm"
)

func AddDataFileHandler(db *gorm.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Println("Received request at /create-datafile")
log.Println("Received request at /create-datafile")

if err := utils.CheckRequestMethod(r, http.MethodPost); err != nil {
utils.SendJSONError(w, err.Error(), http.StatusBadRequest)
Expand All @@ -29,7 +31,7 @@ func AddDataFileHandler(db *gorm.DB) http.HandlerFunc {
utils.SendJSONError(w, "Error parsing multipart form", http.StatusBadRequest)
return
}
fmt.Println("Parsed multipart form")
log.Println("Parsed multipart form")

file, _, err := r.FormFile("file")
if err != nil {
Expand All @@ -40,10 +42,8 @@ func AddDataFileHandler(db *gorm.DB) http.HandlerFunc {

walletAddress := r.FormValue("walletAddress")
filename := r.FormValue("filename")
publicBool := r.FormValue("public")
visibleBool := r.FormValue("visible")

fmt.Printf("Received file upload request for file: %s, walletAddress: %s, public: %s, visible: %s\n", filename, walletAddress, publicBool, visibleBool)
log.Printf("Received file upload request for file: %s, walletAddress: %s \n", filename, walletAddress)

tempFile, err := utils.CreateAndWriteTempFile(file, filename)
if err != nil {
Expand All @@ -65,13 +65,9 @@ func AddDataFileHandler(db *gorm.DB) http.HandlerFunc {
Timestamp: time.Now(),
}

// if result := db.Create(&dataFile); result.Error != nil {
// utils.SendJSONError(w, fmt.Sprintf("Error saving datafile: %v", result.Error), http.StatusInternalServerError)
// return
// }

result := db.Create(&dataFile)
if result.Error != nil {
log.Println("error saving to DB")
if utils.IsDuplicateKeyError(result.Error) {
utils.SendJSONError(w, "A data file with the same CID already exists", http.StatusConflict)
} else {
Expand Down
2 changes: 0 additions & 2 deletions gateway/models/datafile.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,4 @@ type DataFile struct {
WalletAddress string `gorm:"type:varchar(42);not null"`
Filename string `gorm:"type:varchar(255);not null"`
Timestamp time.Time `gorm:""`
Domain string `gorm:"default:public"`
Visible bool `gorm:"default:true"`
}
11 changes: 9 additions & 2 deletions gateway/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
Expand All @@ -12,12 +13,18 @@ import (
func SendJSONError(w http.ResponseWriter, message string, status int) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(map[string]string{"message": message})
if err := json.NewEncoder(w).Encode(map[string]string{"message": message}); err != nil {
log.Printf("Could not encode JSON: %v", err)
}
}

func SendJSONResponseWithCID(w http.ResponseWriter, cid string) {
response := map[string]string{"cid": cid}
jsonResponse, _ := json.Marshal(response)
jsonResponse, err := json.Marshal(response)
if err != nil {
SendJSONError(w, fmt.Sprintf("Error encoding response to JSON: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(jsonResponse)
}
Expand Down

0 comments on commit acd9686

Please sign in to comment.