functions to serialize an object to querystring and the deserialize the query string back to objectze query strings
npm install gt-query-stringserializeObject gets an object or array nested in an object and returns a query string from it
javascript
{ name:'xxx', start:123 }
`
will return
`
?name=xxx&start=123
`
the array
`javascript
{ list:[4,5,6] }
`
will return
`
?list[0]=4&list[1]=5&list[2]=6
`
an embedded object
`javascript
{ person:{ name:'xxx', id:123 } }
`
will return ?person.name=xxx&person.id:123
an array that contains an object
`javascript
{ 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:
`javascript
{ 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
1. desrializeObject : gets an encoded querystring and returns the original object.
2. 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 the desQuery property of the request
how to use the package
1. install the package
`javascript
npm i gt-query-string
`
2. client side
use the serializeObject function, and send the request with the approriate headers
`javascript
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(, {method: 'GET', headers:{...options}}).then(...)
`
3. server side - express can be used with js and ts
app.js
`javascript
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)
});
`
app.ts
`javascript
import express from 'express'
import {deserializeURI} from 'gt-query-string';
app = express()
app.get('/data', deserializeURI(), (req:Request, res: Response, next: NextFunction)=>{
console.log(req.desQuery);
const query: object = req.desQuery;
res.status(200);
});
``