Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Keeping nesting with custom decoder ? #454

Open
Altho opened this issue Nov 14, 2022 · 1 comment
Open

Keeping nesting with custom decoder ? #454

Altho opened this issue Nov 14, 2022 · 1 comment

Comments

@Altho
Copy link

Altho commented Nov 14, 2022

Hello,

I am using parse() on a node server (vanilla node http server, not express) to parse a long, not known in advance, querrystring to JSON. I also need to convert the values to the correct type. I understand that qs doesn't do type coercion by design. Here is my issue

If i just use parse without options every value is a string but my nested values are correctly displayed. But if I use a custom decoder to convert the types :

const data = qs.parse(body, {
        decoder(value) {
          if (/^(\d+|\d*\.\d+)$/.test(value)) {
            return parseFloat(value);
          }

          const keywords: Record<string, any> = {
            true: true,
            false: false,
            null: null,
            undefined: undefined,
          };

          if (value in keywords) {
            return keywords[value];
          }

          return value;
        },
      });

then I lost nesting. How do I manage to keep the nesting along type coercion ?

@ljharb
Copy link
Owner

ljharb commented Nov 16, 2022

First, i would suggest not using in, since your keywords inherits from Object.prototype - use Object.hasOwn (https://npmjs.com/object.hasown).

Separately, the issue is that you're not using the decoder correctly. Try this:

const keywords: Record<string, any> = {
  __proto__: null,
  true: true,
  false: false,
  null: null,
  undefined: undefined,
};

const data = qs.parse(body, {
  decoder(value, defaultDecoder, ...rest) {
    if (/^(\d+|\d*\.\d+)$/.test(value)) {
      return parseFloat(value);
    }

    if (Object.hasOwn(keywords, value)) {
      return keywords[value];
    }

    return defaultDecoder(value, ...rest);
  },
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants