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

How to dispatch one argument to multiple function in fp-ts

我有以下代码

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
    })),
  );