Skip to content

Commit 92c746b

Browse files
gomainljharb
authored andcommittedJul 13, 2022
[readme] add usage of filter option for injecting custom serialization, i.e. of custom types.
1 parent 56763c1 commit 92c746b

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
 

‎README.md

+38
Original file line numberDiff line numberDiff line change
@@ -498,6 +498,44 @@ qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] });
498498
// 'a[0]=b&a[2]=d'
499499
```
500500

501+
You could also use `filter` to inject custom serialization for user defined types. Consider you're working with
502+
some api that expects query strings of the format for ranges:
503+
504+
```
505+
https://domain.com/endpoint?range=30...70
506+
```
507+
508+
For which you model as:
509+
510+
```javascript
511+
class Range {
512+
constructor(from, to) {
513+
this.from = from;
514+
this.to = to;
515+
}
516+
}
517+
```
518+
519+
You could _inject_ a custom serializer to handle values of this type:
520+
521+
```javascript
522+
qs.stringify(
523+
{
524+
range: new Range(30, 70),
525+
},
526+
{
527+
filter: (prefix, value) => {
528+
if (value instanceof Range) {
529+
return `${value.from}...${value.to}`;
530+
}
531+
// serialize the usual way
532+
return value;
533+
},
534+
}
535+
);
536+
// range=30...70
537+
```
538+
501539
### Handling of `null` values
502540

503541
By default, `null` values are treated like empty strings:

0 commit comments

Comments
 (0)
Please sign in to comment.