Skip to content

Instantly share code, notes, and snippets.

@nico2che
Last active November 6, 2019 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nico2che/33642b6cf051059bc19113f373a73987 to your computer and use it in GitHub Desktop.
Save nico2che/33642b6cf051059bc19113f373a73987 to your computer and use it in GitHub Desktop.
function encode(str) {
return encodeURIComponent(str).replace(
/[!'()*]/g,
x =>
`%${x
.charCodeAt(0)
.toString(16)
.toUpperCase()}`
);
}
function formatter(key, value) {
return value === null
? encode(key)
: [encode(key), "=", encode(value)].join("");
}
function stringify(obj) {
if (!obj) {
return "";
}
return Object.keys(obj)
.map(key => {
const value = obj[key];
if (value === undefined) {
return "";
}
if (Array.isArray(value)) {
const result = [];
for (const element of value.slice()) {
if (element !== undefined) {
result.push(formatter(key, element));
}
}
return result.join("&");
}
return formatter(key, value);
})
.filter(x => x.length > 0)
.join("&");
}
var params = {
l_from: 'en',
l_to: 'fr',
words: JSON.stringify([{ t: 1, w: 'Hello' }]),
request_url: window.location.href,
api_key: "wg_xxxx"
};
// GET request with whole object in URL
fetch(`https://cdn-api.weglot.com/translate?${stringify(params)}`).then(console.log)
/*
{
"l_from": "en",
"l_to": "fr",
"bot": 0,
"title": "",
"request_url": "https://cdn-api.weglot.com/translate",
"from_words": [
"Hello"
],
"to_words": [
"Bonjour"
]
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment