如何避免在fp-ts中嵌套Monad或优雅地处理它们?

时间:2019-02-12 12:20:19

标签: typescript functional-programming monads fp-ts

我有一系列代码,需要执行以下步骤(伪代码):

  jobsRepository.findById // <-- this returns a TaskEither
  jobs.openJob // <-- jobs.openJob returns an Either
  jobsRepository.update // <-- this returns another TaskEither
  createJobOpenedEvent // simple function that returns an IJobOpenedEvent
                       // given an IOpenJob

如果将这些步骤映射/链接在一起,我最终会得到类似TaskEither<IError, Either<IError, TaskEither<IError, IOpenJob>>>的类型,这显然有点尴尬。

我目前将所有这些压缩为简单的TaskEither<IError, IJobOpenedEvent>类型的解决方案如下(真实代码):

import { flatten } from "fp-ts/lib/Chain";
import { Either, either, left, right } from "fp-ts/lib/Either";
import {
  fromEither,
  TaskEither,
  taskEither,
  tryCatch,
} from "fp-ts/lib/TaskEither";

const createJobOpenedEvent = (openJob: jobs.IOpenJob): IJobOpenedEvent => ({
  name: "jobOpened",
  payload: openJob,
});

export const openJobHandler = (
  command: IOpenJobCommand
): TaskEither<IError, IJobOpenedEvent> =>
  flatten(taskEither)(
    flatten(taskEither)(
      jobsRepository
        .findById(command.jobId) // <-- this returns a TaskEither<IError, IJob>
        .map(jobs.openJob) // <-- jobs.openJob returns an Either<IError, IOpenJob>
        .map(fromEither)
        .map(jobsRepository.update) // <-- this returns a TaskEither<IError,IOpenJob>
    )
  ).map(createJobOpenedEvent);


我的问题是-是否有更好的方法来处理此嵌套?我感觉自己做错了,因为我不熟悉函数式编程,也不了解所有理论。对所有嵌套的flatten(taskEither)进行调用并将Either转换为TaskEither的{​​{1}}对我来说似乎很糟糕。

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

感谢Bergi的评论,我能够使用chain而不是map找到以下解决方案:

export const openJobHandler = (
  command: IOpenJobCommand
): TaskEither<IError, IJobOpenedEvent> =>
  jobsRepository
    .findById(command.jobId)
    .map(jobs.openJob)
    .chain(fromEither)
    .chain(jobsRepository.update)
    .map(createJobOpenedEvent)