Have you ever found yourself needing to connect to a legacy PHP API that requires the usage of http_build_query
with RFC1738?
This library will enable you to do so with ease 🍺
- NodeJS 14.x
Install using either npm
or yarn
npm i @modularitybg/http_build_query
//or
yarn add @modularitybg/http_build_query
const httpBuildQuery = require('@modularitybg/http_build_query');
const rfcFormattedQuery = httpBuildQuery({
amount: { amount: 2900 },
stringValueWithWhiteSpace: "String Value",
city: "Unlandstraße",
arrayValues: [1, "string"],
})
``
//Result
"amount=%7B%22amount%22%3A2900%7D&stringValueWithWhiteSpace=String+Value&city=Unlandstra\\u00dfe&arrayValues=%5B1%2C%22string%22%5D"
Notice that special characters are transformed using UTF-8 mapping, similar to how is handled in PHP
Let's compare the difference:
nativeQueryResult = new URLSearchParams({
amount:{
amount: 2900
},
stringValueWithWhiteSpace: "String Value",
city: "Unlandstraße",
arrayValues: [1, "string"]
}).toString()
//Result
'amount=%5Bobject+Object%5D&stringValueWithWhiteSpace=String+Value&city=Unlandstra%C3%9Fe&arrayValues=1%2Cstring'
This type of encoding may not be compatible with the API you are trying to connect. Notice the Object, arrayValues definitions and the special character in the city name.
MIT