Skip to content

Instantly share code, notes, and snippets.

@sangheestyle
Last active November 26, 2018 22:06
Show Gist options
  • Save sangheestyle/22de78f663b8c7a482e196065111b661 to your computer and use it in GitHub Desktop.
Save sangheestyle/22de78f663b8c7a482e196065111b661 to your computer and use it in GitHub Desktop.
Curried function for request promise
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' } ]​​​​​
*/
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