Skip to content

Instantly share code, notes, and snippets.

@dwwoelfel
Last active September 7, 2022 17:00
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 dwwoelfel/ba77380392faa018d94571401c61d87e to your computer and use it in GitHub Desktop.
Save dwwoelfel/ba77380392faa018d94571401c61d87e to your computer and use it in GitHub Desktop.
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