ljharb / qs

A querystring parser with nesting support
BSD 3-Clause "New" or "Revised" License
8.54k stars 728 forks source link

Allow custom value stringify #446

Closed gomain closed 2 years ago

gomain commented 2 years ago

I have a case where a backend accepts values say for a key created accepts a date range of the format:

https://domain.com/endpoint?created=2000-01-01T11:22:33Z...2000-01-01T11:22:33Z

For that I have a custom type

type DateRange = {
  from: Date,
  to: Date,
};

And my query type:

type Query = {
  created: DateRange,
  somethingElse: unknown,
};

Now passing this to qs I need to:

  const query: Query = { .. };
  const seflImplementedStringify(rage: DateRange): string = .. ;
  const queryString = qs.stringify({
     ...query,
    // override `created`
    created: selfImplementedStringify(query.created),
  });

Now this gets cumbersome when DateRange is reused across multiple api, multiple keys, ...

I request feature that would allow this:

const queryString = qs.stringify(
    query,
    {
      serializer: (value: unknown) => {
          if (isDateRagne(value)) {
            return selfImplementedStringify(value);
          }
          return SENITAL_TO_INDICATE_LET_QS_DO_ITS_THING;
        },
      },
    },
  );

or perhaps

const queryString = qs.stringify(
    query,
    {
      serializers: [
          [ isDateRange, selfImplementedStringify ],
      ],
    },
  );

This would allow any sort of custom serialization to be handled in user land. On top of the great defaults and options that qs already provides. Not just for Dates.

gomain commented 2 years ago

OK, this feature is actually available through the filter option.

  const queryString = qs.stringify(
    query,
    {
      filter: (prefix: string, value: unknown) => {
          if (isDateRagne(value)) {
            return selfImplementedStringify(value);
          }
          return value;
        },
      },
    },
  );

This would have been more obvious had the option was named filterMap.

gomain commented 2 years ago

created #447 and #448

ljharb commented 2 years ago

Sounds like your issue was resolved.