fp-ts中基于分页API的惰性递归流

6
我的目标是向API请求交易并将其存储到数据库中。响应是分页的,我想读取每一页并批量存储交易。
所以,在一个请求/响应周期中,我希望在获取下一批前处理结果并将其存储到数据库中。
在fp-ts中,如何以惯用方式实现这一点?我将实际的HTTP fetch调用作为(url:string, init:RequestInit) => TE.TaskEither<Error, Response>注入,以使其可测试。
到目前为止,我已经尝试了RxJS和fp-ts,并且即使我让它们正常工作,也有些复杂。
我尝试了递归函数和生成器,但我没有成功地使其懒惰地求值。
在fp-ts中是否有任何现有的示例,显示了一个懒惰地求值的流,其中每个元素都依赖于前一个元素?
1个回答

0
你可以使用StateReaderTaskEither。 假设你想要读取一个文件列表,并且下一个文件名存储在当前文件中。
import * as TE from 'fp-ts/TaskEither'
import * as RA from 'fp-ts/ReadonlyArray'
import { pipe } from 'fp-ts/function'

const files = {
  file1: 'file2',
  file2: 'file3',
  file3: 'file5',
  file4: 'file6',
  file5: 'file4',
}
const getFile = (filename: string, encoding: string) =>
  Promise.resolve(files[filename])

const fileSRTE: SRTE.StateReaderTaskEither<
  string,
  string,
  unknown,
  string
> = (filename: string) => (encoding: string) =>
  pipe(
    TE.tryCatch(
      () => getFile(filename, encoding),
      (err) => err
    ),
    TE.map((file) => [`file: ${file}`, file])
  )

const fileStream: TE.TaskEither<
  unknown,
  readonly string[]
> = pipe(
  RA.replicate(6, fileSRTE),
  SRTE.sequenceArray,
  SRTE.evaluate('file1')
)('utf-8')

fileStream().then(console.log)
//{ _tag: 'Right',right: [ 'file: file2','file: file3','file: file5','file: file4','file: file6','file: undefined' ] }

你可以在 fp-ts Doc 中进一步了解 State 和 Reader。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接