Skip to content

Instantly share code, notes, and snippets.

@kritzcreek
Created December 3, 2020 12:10
Show Gist options
  • Save kritzcreek/72a02656163c722c78ad8e472a25bcda to your computer and use it in GitHub Desktop.
Save kritzcreek/72a02656163c722c78ad8e472a25bcda to your computer and use it in GitHub Desktop.
Pagination Example
module Main where
import Prelude
import Effect (Effect)
import Effect.Aff (Aff, launchAff_)
import Effect.Class (liftEffect)
import Effect.Class.Console as Console
import Effect.Ref (Ref)
import Effect.Ref as Ref
import TryPureScript (render, withConsole)
type Response = { body :: Array String, done :: Boolean }
fakeAPI :: Int -> Aff (Aff Response)
fakeAPI pages = do
remaining <- liftEffect (Ref.new pages)
pure do
remaining' <- liftEffect (Ref.read remaining)
if remaining' < 1
then pure { body: ["final chunk"], done: true }
else do
liftEffect (Ref.modify_ (_ - 1) remaining)
pure { body: ["chunk: " <> show (pages - remaining')], done: false }
requestPages :: Aff Response -> Aff (Array String)
requestPages api = do
result <- liftEffect (Ref.new [])
go result
where
go :: Ref (Array String) -> Aff (Array String)
go result = do
{ body, done } <- api
liftEffect (Ref.modify_ (_ <> body) result)
if done then liftEffect (Ref.read result) else go result
main :: Effect Unit
main = render <=< withConsole $ launchAff_ do
api <- fakeAPI 10
chunks <- requestPages api
Console.logShow chunks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment