How to Handle File URL Encoding/Decoding in PATCH Request to Avoid GCS NoSuchKey Error?

26 views Asked by At

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)

Array 0 https://storage.googleapis.com/bucket/folnder/name/file_8425f9fe-3291-4256-8b16-d2e3d6d9e0ff.jpeg?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=dataapi%40direct-plasma-296809.iam.gserviceaccount.com%2F20240322%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20240322T123347Z&X-Goog-Expires=900&X-Goog-SignedHeaders=host&X-Goog-Signature=713ea5b88b7729c9397291ac2a5f7bd57c129d19b416da1b944a132f641e95896de8c43d62cafa9bb751f4ee08cb5cca282452239228b753ccac07678fcdef7ffab73eb208b1aaefcfabf481c10339081f39c39df5e17c73311a9d03678d0da91a2545532c

String

qualificationsCertification Array (1)

Array

englishProficiencyTest Array (1)

I am expecting that the existing file will be returned unaltered.

0

There are 0 answers