@calmdownval/oas-serialize v2.0.0
OAS Serialize
This module uses the ES modules feature and requires Node v8.15.0+. Please refer to Node's documentation to read more on how to enable this functionality in your environment.
This module provides multiple styles of serialization and deserialization according to the Open API specification, version 3.
Installation
npm i --save @calmdownval/oas-serialize
Usage
import * as oas from '@calmdownval/oas-serialize';
// first, prepare (de)serialization strategy from the OAS format
// you can also pass in an array of parameter definitions, but they
// all have to share the same ParameterLocation (the `in` parameter)
const strategy = oas.prepare(
{
name: 'ids',
in: oas.ParameterLocation.QUERY,
// this will use the default style 'form' with explode=TRUE
});
// the above corresponds to standard query string serialization
// returns: '?ids=1&ids=2&ids=3'
const str = oas.serialize({ ids: [ 1, 2, 3 ] }, strategy);
You can deserialize the data back using the same strategy. Please note that internally the library
works with key-value-key-value-...
arrays since in some cases it is possible to have duplicate
keys and is why the deserialize
method returns such an array. To convert it back to object you
can use the included a2o
method. Keep in mind that it will scrap any duplicate keys and will use
the last value for such key in the array.
Continuing the example from above:
// returns: [ 'ids', [ '1', '2', '3' ] ]
const raw = oas.deserialize(str, strategy);
// conversion to object
// returns: { ids: [ '1', '2', '3' ] }
const obj = oas.a2o(raw);
Also note that the library makes no effort to detect data types. Even if numbers were serialized, the deserialized form will always be stringified. It is up to the user to parse these out.
Supported styles
- PATH
simple
(default)label
matrix
- QUERY
form
(default)spaceDelimited
pipeDelimited
- HEADER
simple
(default)
- COOKIE
form
(default)
If not specified, explode
defaults to true
for QUERY parameters and to false
for all other
types.
Note:
Most serialization styles with explode
set to false
generate equivalent strings for both
objects and appropriately chosen even-length arrays. The deserialization of such parameters
is thus ambiguous. To avoid this, the library recognizes an extension option x-prefer-array
which defaults to false
. If set to true, even-length lists and single values are returned
as array rather than objects and strings, respectively. Serialization styles affected:
- path: simple, label, matrix
- query: form
- header: simple
- cookie: form
Note:
Query string can contain multiple parameters at once. When an object is serialized using the form
style with explode
set to true
, the object's keys may overlap with other parameters. To avoid
this, when using the form style with explode, only one such parameter will be allowed.
Note:
The deepObject
style for query parameters is currently not supported