1

我有以下代码

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()retun

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

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

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

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

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

因为里面的getFileContents函数chain(getFileContents)需要读取文件,所以我不想读取这个文件两次

4

1 回答 1

2

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

由于您需要 amatter.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
    })),
  );
于 2021-05-18T09:46:04.753 回答