Search code examples
functional-programmingecmascript-6promisecomposition

how to pipe functions, when a promise in the promise in the middle checks authorization?


i'm trying to compose some functions together:

compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));

checkAuthorization returns a promise that check if a user is authorized. buildParams receives someRequestData, and pipes the result to searchItem.

    checkAuthorization()
      .then(() => {
            compose(
                searchItem,
                buildParams
            )(someRequestData)
    }, (e) => {
       handleError(e)
    })

I think it's OK, but I wish to have a more elegant look for readability, something like:

    compose(
      searchItem,
      checkAuthorization
      buildParams
    )(someRequestData)

so what will happen is: 1) build params 2) checkAuth 3) search item

Any suggestions?


Solution

  • No, that's not possible, since checkAuthorisation does not receive and pass through the params. And even if you would rewrite it to do that, it still would be weird and a reader would assume that you're building the params whose authorisation should be checked. So don't do that - you have a non-linear flow, and trying to force it into some linear composition is no good.

    Btw, I would recommend to avoid compose when you're calling the function immediately anyway:

    checkAuthorization().then(() =>
      searchItem(buildParams(someRequestData))
    , e =>
       handleError(e)
    );
    

    or maybe

    checkAuthorization().then( compose(searchItem, buildParams, ()=>someRequestData)
                             , handleError ); //                ^^^^ "const"