Last active
November 6, 2019 14:55
-
-
Save nico2che/33642b6cf051059bc19113f373a73987 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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