I'm learning fp-ts and am wondering how can I better organize my functions to avoid nested folds. All of the examples I see online have a nice streamlined pipe function invocation, but I can't figure out how to avoid the nested folds.
Some context - At a high level, the intent of this code is to create a Location and if that succeeds, create a Station. If either operation fails, return back an appropriate error to the caller. If all is well, return a 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);
}