Search code examples
httphaskellasynchronousservant

How to (asynchronously) consume a steaming end-point generated with servant's StreamGenerators?


The servant documentation describes how to create streaming endpoints:

type StreamAPI = "userStream" :> StreamGet NewlineFraming JSON (StreamGenerator User)
streamAPI :: Proxy StreamAPI
streamAPI = Proxy

streamUsers :: StreamGenerator User

Now the question is how can a client (written in javascript for instance) consume the end-point in an asynchronous fashion?


Solution

  • Note: that in newer servant (0.15 IIRC) streaming was refactored. However, the question of how to consume streaming endpoints in JavaScript is irrelevant of backend implementation.

    For example if you use Fetch API, you can use reader API, which is well explained in MDN. Summarizing that:

    // Fetch the original image
      fetch('./tortoise.png')
      // Retrieve its body as ReadableStream
      .then(response => {
        const reader = response.body.getReader();
    

    Then you can call reader.read() to get response in parts.