Skip to content

Handling of empty objects and arrays #336

@fmang

Description

@fmang

Greetings, and thank you for the gem!

I have noted that calling foo_path({ a: [], b: {} }) generates ?& at the end of the URL, while the query should be empty instead. This is probably not broken but quite ugly.

Reading default_serializer, I suggest rewriting it like this:

        default_serializer(value) {
            const result = [];
            const serialize = (value, prefix) => {
                if (this.is_nullable(value)) {
                    return;
                }
                if (!prefix && !this.is_object(value)) {
                    throw new Error("Url parameters should be a javascript hash");
                }
                prefix = prefix || "";
                if (this.is_array(value)) {
                    for (const element of value) {
                        serialize(element, prefix + "[]");
                    }
                }
                else if (this.is_object(value)) {
                    for (let key in value) {
                        if (!hasProp(value, key))
                            continue;
                        let prop = value[key];
                        if (this.is_nullable(prop) && prefix) {
                            prop = "";
                        }
                        if (this.is_not_nullable(prop)) {
                            if (prefix) {
                                key = prefix + "[" + key + "]";
                            }
                            serialize(prop, key);
                        }
                    }
                }
                else {
                    if (this.is_not_nullable(value)) {
                        result.push(encodeURIComponent(prefix) + "=" + encodeURIComponent("" + value));
                    }
                }
            };
            serialize(value);
            return result.join("&");
        }

Instead of join-ing join-ed values recursively, the result.push for scalar values goes straight to the final result, making the serialize sub-function void. The other calls to result.push become simple recursive calls to serialize instead.

Not knowing your testing process, I am shy for an MR.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions