I'm encountering an issue related to URL encoding/decoding during a PATCH request.
Here's the scenario:
Upon submitting a PATCH request to update a resource, existing files should be returned unaltered. However, after the PATCH is requested, I'm receiving a NoSuchKey error, indicating that the existing files are not being recognized. The file names are correct, but parameters have been encoded. Here's a snippet of my code:
javascript
// Handle PATCH request
const handlePatchForm = () => {
// PATCH request logic...
fetch(process.env.NEXT_PUBLIC_APP_API_URL + `/client/users/${id}`, {
method: "PATCH",
headers: new Headers({
Authorization: "Bearer " + token,
"Content-Type": "application/json",
}),
body: JSON.stringify({
...form,
.....
}),
})
.then((res) => res.json())
.then((json) => {
setForm(json);
toast.success("Form updated successfully!");
})
.catch((error) => {
console.error("Error occurred during PATCH request:", error);
});
};
const handleUpdateForm = (path: string, value: any) => {
let newForm = { ...form };
const keys: any = path.split(".");
const last: any = keys.pop();
keys.reduce((o: any, k: any) => (o[k] ??= {}), newForm)[last] = value;
setForm(newForm);
};
const handleCapture = (target: any, key: string) => {
if (target.files && target.files.length > 0) {
if (target.files[0].size > 5242880) {
alert("File is too big");
throw new Error("File size exceeds the limit");
} else {
const file = target.files[0];
// Get the existing files
const existingFiles = form.files[key] || [];
// Check if the file is new or existing
const isExistingFile = existingFiles.some(
(existingFile: string) => existingFile === file
);
if (!isExistingFile) {
// If the file is new, read the file content and convert to base64
const reader = new FileReader();
reader.onloadend = () => {
const base64Content = reader.result?.toString();
const fileType = base64Content?.split(";")[0].split("/")[1];
// Log the base64 content and file type for debugging
console.log(`Base64 Content (${key}):`, base64Content);
console.log(`File Type (${key}):`, fileType);
// Check if both base64Content and fileType are defined before proceeding
if (base64Content && fileType) {
target.value = "";
const updatedFiles = [
...existingFiles,
{ title: file.name, uri: base64Content },
];
// Update form state to include the array of files
handleUpdateForm(`files.${key}`, updatedFiles);
} else {
// Handle the case when base64Content or fileType is undefined
console.error("Error: Undefined base64 content or file type");
// Optionally show an error message to the user
}
};
reader.readAsDataURL(file);
}
}
} else {
// Handle the case when files are removed and input is empty
handleUpdateForm(`files.${key}`, []);
}
};
I am using Feathers.js for the backend. The context.data.files is showing the working URLs
DB: files Object
Object
resume Array (1)
String
qualificationsCertification Array (1)
Array
englishProficiencyTest Array (1)
I am expecting that the existing file will be returned unaltered.