firecms icon indicating copy to clipboard operation
firecms copied to clipboard

Fully optional maps

Open ciriousjoker opened this issue 2 years ago • 3 comments

interface Test {
  prop?: {
    subprop: string;
  }
}

How can I define prop as fully optional. Basically, either prop has to be undefined or all subproperties are required.

Right now, I can't find a way to make the whole property undefined (not even with onPreSave).

ciriousjoker avatar Nov 07 '22 14:11 ciriousjoker

Hi @ciriousjoker I have been trying to make this work using yup which is the validation library we use and could not find an easy way. I am pretty sure it can be done. If you want, you can give us a hand by finding a yup config that satisfies your criteria :) https://github.com/jquense/yup#object

fgatti675 avatar Nov 10 '22 20:11 fgatti675

@fgatti675 No idea how yup works, but does this help? https://github.com/jquense/yup/issues/772

ciriousjoker avatar Nov 10 '22 20:11 ciriousjoker

It does, thanks! So this is my best attempt to implement a yup config like the one you describe, but it still doesn't work as expected. If anyone can make it work, I'm happy to add it to the code:

    const object: ObjectSchema<any> = yup.object().shape(objectSchema);
    return validation?.required
        ? object.required(validation?.requiredMessage ? validation.requiredMessage : "Required").nullable(true)
        : yup.object().optional().default(undefined).notRequired().nullable(true).test(
            "empty-check",
            "Optional map can be empty",
            (o: any, testContext: any) => {
                try {
                    if (!o || Object.keys(o).length === 0) return true;
                    return object.validateSync(o);
                } catch (e) {
                    testContext.createError(e);
                    console.error(e);
                    return false;
                }
            });
            ```

fgatti675 avatar Nov 13 '22 19:11 fgatti675

Latest version has a key/value option that allows input of arbitrary data

fgatti675 avatar Mar 14 '24 00:03 fgatti675