我有一系列代码,需要执行以下步骤(伪代码):
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}}对我来说似乎很糟糕。
非常感谢您的帮助!
答案 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)