Last active
November 26, 2018 22:06
-
-
Save sangheestyle/22de78f663b8c7a482e196065111b661 to your computer and use it in GitHub Desktop.
Curried function for request promise
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 rp = require('request-promise'); | |
// A curried function | |
const fetch = (serverUrl) => | |
(endpointPath) => | |
async (id) => { | |
const options = { | |
uri: `${serverUrl}/${endpointPath}/${id}`, | |
json: true, | |
// some of common settings | |
}; | |
return await rp(options); | |
}; | |
const catAppApiClient = fetch('https://catappapi.herokuapp.com'); | |
const catsClient = catAppApiClient('cats'); | |
const usersClient = catAppApiClient('users'); | |
(async () => { | |
const user = await usersClient(123); | |
const cats = await Promise.all(user.cats.map(id => catsClient(id))); | |
console.log(user); | |
console.log(cats); | |
})(); | |
/* | |
{ name: 'mpj', | |
cats: [ 21, 33, 45 ], | |
imageUrl: 'http://images.somecdn.com/user-123.jpg' } | |
[ { name: 'Fluffykins', | |
imageUrl: 'http://images.somecdn.com/cat-21.jpg' }, | |
{ name: 'Waffles', | |
imageUrl: 'http://images.somecdn.com/cat-33.jpg' }, | |
{ name: 'Sniffles', | |
imageUrl: 'http://images.somecdn.com/cat-45.jpg' } ] | |
*/ |
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 R = require('ramda'); | |
const rp = require('request-promise'); | |
// A normal function | |
const fetch = async (serverUrl, endpointPath, id) => { | |
const options = { | |
uri: `${serverUrl}/${endpointPath}/${id}`, | |
json: true, | |
// some of common settings | |
}; | |
return await rp(options); | |
}; | |
// A curried function | |
const curriedFetch = R.curry(fetch); | |
const catAppApiClient = curriedFetch('https://catappapi.herokuapp.com'); | |
const catsClient = catAppApiClient('cats'); | |
const usersClient = catAppApiClient('users'); | |
(async () => { | |
const user = await usersClient(123); | |
const cats = await Promise.all(user.cats.map(id => catsClient(id))); | |
console.log(user); | |
console.log(cats); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment