gt-query-string
v1.1.0
Published
functions to serialize an object to querystring and the deserialize the query string back to objectze query strings
Downloads
6
Readme
gt-query-string
An public module to serialize and deserialize a query string.
serialize an object to query string
The function serializeObject
gets an object or array nested in an object and returns a query string from it
the object
{ name:'xxx', start:123 }
will return
?name=xxx&start=123
the array
{ list:[4,5,6] }
will return
?list[0]=4&list[1]=5&list[2]=6
an embedded object
{ person:{ name:'xxx', id:123 } }
will return ?person.name=xxx&person.id:123
an array that contains an object
{ or:[{ item:10, point:3 }, { name:5} ]}
will return
?or[0]item=10&or[0]point:3&or[1]name=5`
The function seializeObject
returns the following object:
{ query, options}
the options contains the data that needs to be sent as headers in the request.
deserialize an object from the query string object
There are two opptions to deserialize the object
desrializeObject
: gets an encoded querystring and returns the original object.- an express middleware that deserializes the querystring back to the original object. The request must contain the following headers:
{'query-serialize' : 'gt'}
. The deseialized object is stored in thedesQuery
property of the request
how to use the package
- install the package
npm i gt-query-string
- client side use the serializeObject function, and send the request with the approriate headers
const {serializeObject} = require('gt-query-string');
const obj = {type:'triangle', points:[{x:0, y:10}, {x:15, y:45}, {x:30, y:12}] };
const {query, options} = serializeObject(obj);
fetch(`<serverurl>${query}`, {method: 'GET', headers:{...options}}).then(...)
- server side - express can be used with
js
andts
const express = require('express')
const {deserializeURI} = require('gt-query-string');
app = express()
app.get('/data', deserializeURI(), (req, res, next)=>{
console.log(req.desQuery);
res.status(200)
});