Skip to content

Instantly share code, notes, and snippets.

@laphilosophia
Created February 21, 2019 13:39
Show Gist options
  • Save laphilosophia/d2c273ce8f78797bb297887728972ca9 to your computer and use it in GitHub Desktop.
Save laphilosophia/d2c273ce8f78797bb297887728972ca9 to your computer and use it in GitHub Desktop.
javascript closure example
function apiConnect(apiKey) {
function get(route) {
return fetch(`${route}?key=${apiKey}`)
}
function post(route, params) {
return fetch(route, {
method: 'POST',
body: JSON.stringify(params),
headers: {
'Authorization': `Bearer ${apiKey}`
}
})
}
return { get, post }
}
const api = apiConnect('my-secret-key')
// No need to include the apiKey anymore
api.get('http://www.example.com/get-endpoint')
api.post('http://www.example.com/post-endpoint', { param: 'string' })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment