I'm currently learning functional programming in JavaScript. I use ramda as a helper library to write helpers such as asyncPipe
:
import { pipeWith, then } from 'ramda';
export const asyncPipe = pipeWith(then);
To log the user in I have to make an unauthenticated fetch request with a static url:
export const postRequest = route =>
asyncPipe([
body =>
fetch(route, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}),
getJSON,
]);
Now, since the url is static, I can curry this function and use it in a pipe like this:
export const login = asyncPipe([
postRequest(ROUTE_LOGIN),
prop('token'),
setToken,
]); // Will get called with the correct body
So far so good. But now I have to make a request with a dynamic URL, and body and it needs to be authenticated, so I need headers. I'm struggling to write this code so that it is pipeable.
Here is what I tried:
export const postRequestWithAuth = route => body =>
asyncPipe([
getToken,
token =>
fetch(route, {
method: 'POST',
headers: { Authorization: `Token ${token}`, 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}),
getJSON,
]);
But I can't figure out how you would use this with pipe
or compose
(async, of course) because the way I wrote it you would have to do:
postRequestWithAuth(ROUTE_HOUSES + uuid)(body)()
whereas the last call is just to activate the asyncPipe
. As you can see this is very messy and hard to pipe
. How would you solve this in a functional way?