How to make two parallel requests with different error types using sequenceT and ReaderTaskEither?

Viewed 81

I want to make two parallel requests using sequenceT function and work with results, but it shows me an error which I cannot resolve on my own

import * as RTE from 'fp-ts/ReaderTaskEither'
import * as Ap from 'fp-ts/Apply'

Ap.sequenceT(RTE.ApplyPar)(
  getUserById('1'),
  getSpecialistById('2')
) // <- This method shows error

Error

Type 'SpecialistNotFoundError' is not assignable to type 'UserNotFoundError'.
          Types of property 'code' are incompatible.
            Type '"SPECIALIST_NOT_FOUND"' is not assignable to type '"USER_NOT_FOUND"'

Code that may help to understand the problem

function getSpecialistById (specialistId: string): RTE.ReaderTaskEither<PrismaClient, SpecialistNotFoundError, Specialist> {
  return (prisma: PrismaClient) => {
    return TE.tryCatch(
      () => prisma.specialist.findUnique({ where: { id: specialistId }, rejectOnNotFound: true }),
      () => new SpecialistNotFoundError()
    )
  }
}

function getUserById (userId: string): RTE.ReaderTaskEither<PrismaClient, UserNotFoundError, User> {
  return (prisma: PrismaClient) => {
    return TE.tryCatch(
      () => prisma.user.findUnique({ where: { id: userId }, rejectOnNotFound: true }),
      () => new UserNotFoundError()
    )
  }
}

class UserNotFoundError extends Error {
  readonly code = 'USER_NOT_FOUND'

  constructor () {
    super('User not found')
  }
}

class SpecialistNotFoundError extends Error {
  readonly code = 'SPECIALIST_NOT_FOUND'

  constructor () {
    super('Specialist not found')
  }
}
1 Answers

I think rather than using sequenceT (as I don't think it's capable of handling the types correctly for what you're trying to do) I would instead use Do notation like follows:

const result = pipe(
  RTE.Do,
  RTE.apS("user", getUserById("1")),
  RTE.apSW("spec", getSpecialistById("2")),
  RTE.map(({ user, spec }) => {
    return `${user.id}:${spec.id}`;
  })
);

result will be RTE.ReadTaskEither<PrismaClient, UserNotFoundError | SpecialistNotFoundError, string> in this case since I returned a string in map.

Here are the docs on Do notation. Note at the bottom where it shows how to do things in parallel

Related