如何在fp-t中将一个参数分派给多个函数



我有以下代码

export const getPostData = (id: string) =>
pipe(
getFullPathFileNameForPosts(`${id}.md`), // IO<string>
chain(getFileContents), // IO<string>
chain(getMatter), // IO<matter.GrayMatterFile<string>>
map(R.pick(['data'])),
bind('id', () => () => id)
);

上述函数getPostData()返回

IO<{
data: {[key: string]: any};
id: string;
}>

现在我必须在返回的结果中添加一些文件,比如content,结果看起来像

IO<{
data: {[key: string]: any};
id: string;
content: string;
}>

我写了一个新函数getContent = (matter: matter.GrayMatterFile<string>) => {...},现在如何将这个函数添加到组合函数getPostData中?

我想问的主要问题是如何将值划分为不同的函数,以便在组合函数中进行处理。

因为chain(getFileContents)中的getFileContents函数需要读取该文件,所以我不想读取两次

您可以继续使用bindbindTo来保留您需要的所有值,直到您使用完它们。

由于需要matter.GrayMatterFile作为getContent函数的输入;保持";这个值会持续更长的时间。

这里有一种可能的方法:

import { pipe} from 'fp-ts/lib/function'
import { chain, map, bind, bindTo, IO, of } from 'fp-ts/lib/IO'
import { GrayMatterFile } from 'gray-matter'
declare const getMatter: (fileContents: string) => IO<GrayMatterFile<string>>
declare const getFileContents: (filepath: string) => IO<string>
declare const getFullPathFileNameForPosts: (filename: string) => IO<string>
declare const getContent: (file: GrayMatterFile<string>) => IO<string>
export const getPostData = (id: string) =>
pipe(
getFullPathFileNameForPosts(`${id}.md`), // IO<string>
chain(getFileContents), // IO<string>
chain(getMatter), // IO<matter.GrayMatterFile<string>>
bindTo('grayMatterFile'),
bind('content', ({ grayMatterFile }) => getContent(grayMatterFile)),
map(({ content, grayMatterFile }) => ({
content: content,
data: grayMatterFile.data,
id
})),
);

最新更新