These are chat archives for ramda/ramda

21st
Dec 2018
Raja Rao DV
@rajaraodv_twitter
Dec 21 2018 22:12
Hello there, Still learning Ramda, how'd you refactor the if-else in the following code?
export const validateFirebaseIdTokenUsingAdmin = curry(
  async (admin, req, res, next) => {
    const token = hasToken(req) ? getToken(req) : false;
    const tokenVerified = token ? await verifyToken(admin, token) : false;
    if(tokenVerified) {
       set(lensProp("user"), tokenVerified, req)
        next()
     } else {
     unauthorized(res);
     }
     console.log('token', tokenVerified)
     return tokenVerified;
  }
);
My problem is that the if-else block has a next function
and I want to test the following in the if logic set(lensProp("user"), tokenVerified, req)
Brad Compton (he/him)
@Bradcomp
Dec 21 2018 22:36

I think you're going to run into a few issues with this code.

The first is that set will not actually mutate your req. It will return a new object that has the updates to req you are making, but Ramda will never mutate your input data.

I would start by recognizing your side effects and isolating them. These are anything the function does outside of returning a value. Ignoring the console logging, they would be mutating the req and calling the callback.

Once we isolate those, the actual logic becomes simple:

const processToken = async (admin, req) => {
  const token = hasToken(req) ? getToken(req) : false;
  return token ? await verifyToken(admin, token) : false;
}

Then we can write a helper function for creating our next function

const _next = (next, req, res, tokenVerified) => tokenVerified ? 
  () => { req.user = tokenVerified; next() } : 
  () => unauthorized(res);

Now we can put it together

export const validateFirebaseIdTokenUsingAdmin = curry(
  async (admin, req, res, next) => {
    const tokenVerified = await processToken(admin, req);
    const run = _next(next, req, res, tokenVerified);
    run();   
    console.log('token', tokenVerified)
    return tokenVerified;
  }
);
Brad Compton (he/him)
@Bradcomp
Dec 21 2018 22:44
You could also parameterize unauthorized for ease of testing that side of things too if that's an issue.
Raja Rao DV
@rajaraodv_twitter
Dec 21 2018 22:50
Thanks Brad! Good point on the mutation part! I wasn't thinking about it!
Also, I like your thought process in refactoring... I'm slowly getting the Ramda bug .. it's so much fun
Brad Compton (he/him)
@Bradcomp
Dec 21 2018 22:52
Thanks! You'll notice I didn't actually use much Ramda at all. It's more the thought patterns than the specific tools we use :bowtie:
Raja Rao DV
@rajaraodv_twitter
Dec 21 2018 22:53
yeah, in fact, you removed some of Ramda :)
Brad Compton (he/him)
@Bradcomp
Dec 21 2018 22:53
:laughing: