Search code examples
javascriptfunctional-programmingsanctuary

Sanctuary js execute 2 steps of pipe with condition


I have a S.pipe for upload and manipulate incoming request file

S.pipe([
    getRequestFile,
    S.chain(saveTemporary),
    S.chain(checkIfIsImage),
    S.chain(addWatermarkToImage),   // only execute on image
    S.chain(copyImageToPublicPath), // only execute on image
    S.chain(copyFileToPath),
    S.chain(formatResponse),
]);

There are 2 specific steps addWatermarkToImage and copyImageToPublicPath that should only execute for image files.

I know I can return Left from checkIfIsImage if the file is not an image but by doing that copyFileToPath and formatResponse are also ignored.

I want to ignore just addWatermarkToImage and copyImageToPublicPath if the file is not image

How can I do that?


Solution

  • The general approach is to use a function such as x => p (x) ? f (x) : g (x). g could be a trivial function such as S.I or S.Right.

    In your case the code would resemble the following:

    S.pipe ([
      getRequestFile,
      S.chain (saveTemporary),
      S.chain (file => file.type === 'image' ?
                       S.chain (copyImageToPublicPath)
                               (addWatermarkToImage (file)) :
                       S.Right (file)),
      S.chain (copyFileToPath),
      S.chain (formatResponse),
    ])
    

    Note that it's necessary to return S.Right (file) rather than file in the non-image case.