我想尝试使用fp-ts重写代码的某些部分,并考虑重构以下方法:
export const createApiServer = () => {
logger.info("Starting World Server API");
const apiServer = express()
// 3rd party middleware
.use(helmet())
.use(bodyParser.json())
.use(cors())
// Root route
.get("/", (_, result) => result.sendStatus(httpStatusCodes.OK))
// 404 - Not Found
.use((_, result) => result.sendStatus(httpStatusCodes.NOT_FOUND))
// 500 - Internal Server Error
.use(errorLoggerMiddleware)
.use(errorResponseMiddleware);
logger.verbose(`Initialized World Server API in ${process.uptime().toFixed(3)} seconds`);
return apiServer;
};
在了解了IO
类型的副作用后,我尝试如下使用它:
const info = (message: string) => new IO(() => log.info(message));
const verbose = (message: string) => new IO(() => log.verbose(message));
const setupApiServer = () =>
new IO(() =>
express()
.use(helmet())
.use(bodyParser.json())
.use(cors())
.get("/", (_, result) => result.sendStatus(httpStatusCodes.OK))
.use((_, result) => result.sendStatus(httpStatusCodes.NOT_FOUND))
.use(errorLoggerMiddleware)
.use(errorResponseMiddleware)
);
export const createApiServer = () =>
info("Starting World Server API")
.chain(setupApiServer)
.chain((apiServer) =>
verbose(`Initialized World Server API in ${process.uptime().toFixed(3)} seconds`)
.map(() => apiServer)
)
.run();
在上一个链调用中随意使用map方法在apiServer对象中进行管道传递只是为了在接收它并进一步发送它之间进行登录,这感觉很奇怪。我想知道这是否正确,或者是否有其他不同的模式。
答案 0 :(得分:0)
您可以使用chainFirst
。
通过chainFirst
,您可以重构
import { pipe } from "fp-ts/lib/pipeable";
import * as IO from "fp-ts/lib/IO";
declare const log: (m: string) => IO.IO<void>
declare const a: IO.IO<number>
pipe(
a,
IO.chain((a) => pipe(log(`Got ${a}`), IO.map(() => a)))
)
进入
pipe(
a,
IO.chainFirst((a) => log(`Got ${a}`))
)