thomasreichmann / upload-thomasar

Simple upload application for sharing files
https://upload-thomasar.vercel.app
0 stars 0 forks source link

improve the deserialization of the values inside "json" collumns in postgress #6

Closed thomasreichmann closed 2 months ago

thomasreichmann commented 2 months ago

currently when some values inside of a json field in postgres are de-serialized, they get converted to strings ie: false becomes "false" this can cause issues where we are trying to check for specific values and not strings.

if (user.settings.autoOpen?.toString() == "true") {
    setTimeout(() => {
        setOpen(true);
    }, user.settings.delay);
}

in this case we need to do this weird conversion and compare against "true" instead of just true because the boolean value gets returned as a string, and even the string "false" gets considered as "thruthy" by JS

the idea is that we want to be able to do just

if (user.settings.autoOpen) {}

thomasreichmann commented 2 months ago

the issue was in how we were saving the values after submitting the form, everything was saved as string, and since json type in postgres doesn't have hard type checking, it just accepted it, ended up going with a kinda hacky solution during form submission

for (const [key, value] of formData.entries()) {
    // Handle sessionId separately
    if (key === "sessionId") {
        sessionId = value as string;
        continue;
    }

    // Detect and handle boolean values
    if (value === "true" || value === "false") {
        (newConfig[key] as unknown as boolean) = value === "true"; // convert to boolean
    }
    // Handle numbers (if applicable)
    else if (!isNaN(Number(value))) {
        (newConfig[key] as unknown as number) = Number(value); // convert to number
    }
    // Default to string
    else {
        newConfig[key] = value as string;
    }
}