【发布时间】:2021-10-29 16:22:16
【问题描述】:
我正在学习 fp-ts,我想知道如何更好地组织我的函数以避免嵌套折叠。我在网上看到的所有示例都有一个很好的流线型 pipe 函数调用,但我不知道如何避免嵌套折叠。
一些上下文 - 概括地说,此代码的目的是创建一个Location,如果成功,则创建一个Station。如果任一操作失败,则将适当的错误返回给调用者。如果一切正常,返回 201。
public async initialize(
@requestParam('site') site: string,
@request() req: Request,
@response() res: Response
) {
//use the same value for now
const nameAndPublicId = LocationService.retailOnlineLocationName(site);
const location: E.Either<ApiError, LocationDTO> = await this.locationService.createLocation(
site,
nameAndPublicId,
nameAndPublicId
);
const stationName: string = StationService.retailOnlineStationName(site);
pipe(
location,
E.fold(
(err: ApiError) => ConfigController.respondWithError(err, res),
async (loc: LocationDTO) => {
pipe(
await this.stationService.createStation(site, stationName, loc.id),
E.fold(
(err: ApiError) => ConfigController.respondWithError(err, res),
(_: StationDTO) => res.status(201).send()
)
);
}
)
);
}
static respondWithError(err: ApiError, res: Response) {
res.status(err.statusCode).json(err);
}
【问题讨论】:
标签: typescript fp-ts