Last active
September 7, 2022 17:00
-
-
Save dwwoelfel/ba77380392faa018d94571401c61d87e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const resolve = (path, json) => { | |
if (Array.isArray(json)) { | |
return json.flatMap((item, i) => resolve([...path, i], item)); | |
} | |
if (typeof json === 'object') { | |
return Object.keys(json).flatMap((k) => resolve([...path, k], json[k])); | |
} | |
if (typeof json === 'string') { | |
return [{path, value: json}]; | |
} | |
throw new Error('Invalid JSON. All leaf values must be strings.'); | |
}; | |
const jsonToAuthsArgHeaders = (json) => { | |
if (Array.isArray(json) || typeof json !== 'object') { | |
throw new Error('Invalid JSON. Expected an object.'); | |
} | |
const pairs = resolve([], json); | |
const result = {}; | |
for (const {path, value} of pairs) { | |
const headerName = 'X-Auths-' + path.join('-'); | |
result[headerName] = value; | |
} | |
return result; | |
}; | |
// Example: | |
// jsonToAuthsArgHeaders({gitHubOAuthToken: 'my-token'}) | |
// => {'X-Auths-gitHubOAuthToken': 'my-token'} | |
export default jsonToAuthsArgHeaders; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment