Categories
javascript typescript

How to achieve validatedNel with fp-ts

fp-ts is a great library, but it can be confusing some times. The last problem that I had was that I didn’t know how to implement validatedNel. Some methods have been deprecated, and the issue answers also didn’t help.

ValidatedNel

validatedNel is used to validate multiple problems and then merge them together into a single error string.

These problems could be transformed into some other object, but for most backend use cases, it is used to return an array of errors which were wrong with user input. For instance, password is too short, userName is too long , where we have 2 errors together.

Solution

The answer is to use the Semigroup and TE.getApplicativeTaskValidation functions to get the Ap constant

let Ap = TE.getApplicativeTaskValidation(T.ApplyPar,
  pipe(string.Semigroup, S.intercalate(", "))
)

After this, you can use pipe and sequenceT from fp-ts/lib/Apply.js to validate your input and get errors in a list.

S.intercalate(", ") from the previous snippet is used to join errors into a single string, eg error1, error2, ...

await pipe(
  sequenceT(Ap)(
    validateFileName(input.fileName),
    validateBucket(input.bucket),
  ),
  TE.mapLeft((it)=> Error(it)),
  TE.map(([fileName, bucket]) => 
    console.log(`doing more work with ${fileName} and ${bucket}`)
  ))()

In this sample, the joined error string is mapped into and Error object which can be used later in different TE flows. Error.message can be used to retrieve the joined error message

Please check out my Github repo for the full solution.