Modeling Nested API Calls
Another weird question, how would you model nested API calls, I'm trying the following (using only Option.ap, not flatMap for now for illustrative purposes) and this fails:
export const getPost = (id: number): Effect.Effect<never, never, Post> =>
Effect.gen(function* (_) {
yield* _(Effect.sleep('0.3 seconds'))
return { id, title: 'Love them futures' }
})
export const getComments = (id: number): Effect.Effect<never, never, string[]> =>
Effect.gen(function* (_) {
yield* _(Effect.sleep('0.3 seconds'))
return ['This book should be illegal', 'Monads are like space burritos']
})
const renderComments = (xs: string[]) =>
xs.reduce((acc: string, c: string): string => `${acc}<li>${c}</li>`, '')
const render =
({ title }: Post) =>
(cs: string[]) =>
`<div>${title}</div><ul>${renderComments(cs)}</ul>`
// renderDOM :: Effect<never,never,HTML>
const renderDOM = pipe(Option.lift2(render), getPost(2), getComments(2))
const html = await Effect.runPromise(renderDOM)
expect(html).toBe(
'<div>Love them futures</div><ul><li>This book should be illegal</li><li>Monads are like space burritos</li></ul>'
)export const getPost = (id: number): Effect.Effect<never, never, Post> =>
Effect.gen(function* (_) {
yield* _(Effect.sleep('0.3 seconds'))
return { id, title: 'Love them futures' }
})
export const getComments = (id: number): Effect.Effect<never, never, string[]> =>
Effect.gen(function* (_) {
yield* _(Effect.sleep('0.3 seconds'))
return ['This book should be illegal', 'Monads are like space burritos']
})
const renderComments = (xs: string[]) =>
xs.reduce((acc: string, c: string): string => `${acc}<li>${c}</li>`, '')
const render =
({ title }: Post) =>
(cs: string[]) =>
`<div>${title}</div><ul>${renderComments(cs)}</ul>`
// renderDOM :: Effect<never,never,HTML>
const renderDOM = pipe(Option.lift2(render), getPost(2), getComments(2))
const html = await Effect.runPromise(renderDOM)
expect(html).toBe(
'<div>Love them futures</div><ul><li>This book should be illegal</li><li>Monads are like space burritos</li></ul>'
)