KDot
KDot

Reputation: 506

Access Arg from Previous Function in Composed Function (using Rambda.pipe)

I have a case where I have a pipeline that fits together nicely, but there is an instance where I need to fire off an async call to an API that I don't control. I don't necessarily care about the result, just whether or not it succeeds, and then would like to continue passing along the arg to that call (not the return value). So my pipeline looks something like this:

const extractUserIdFromResponse = R.andThen( R.prop( user_id ) );
const callExternalApi = tryCatch(
   doApiCall, 
   handleAPIFailure
); 

const pipeline  = R.pipe(
   getRecordFromDatabase, 
   extractUserIdFromResponse, 
   callExternalApi, 
   doSomethingElseWithUserId 
); 

Basically, I want the doSomethingElseWithUserId function to, obviously, accept the userId as the arg as opposed to the result returned from callExternalApi. I'm a little new to this so I'm unsure if I'm on the right track here or not.

Thanks in advance for your help!

Upvotes: 0

Views: 77

Answers (1)

artanik
artanik

Reputation: 2714

I'm also new to ramda, that's why I'm not sure about the accuracy of the answer, but doSomethingElseWithUserId can receive user_id from getRecordFromDatabase through callExternalApi.

https://codesandbox.io/s/affectionate-oskar-kzn8d

import R from "ramda";

const getRecordFromDatabase = () => (
  new Promise((resolve, reject) => {
    return resolve({ user_id: 42 });
  })
);

// I assume that you need to pass the arg here in handleAPIFailure as well
const handleAPIFailure = () => {};
const doApiCall = args => (
  new Promise((resolve, reject) => {
    return resolve(args);
  })
);

const extractUserIdFromResponse = R.andThen(R.prop("user_id"));
const callExternalApi = R.tryCatch(doApiCall, handleAPIFailure);

const doSomethingElseWithUserId = user_id => {
  console.log(user_id); // 42
};

const pipeline = R.pipe(
  getRecordFromDatabase,
  extractUserIdFromResponse,
  callExternalApi,
  R.andThen(doSomethingElseWithUserId)
);

pipeline();

Upvotes: 1

Related Questions