As talked in streaming entrypoints RΞASON, by default, applies a custom encoding to your data.

The custom encoding is only applied you yield objects in a streaming entrypoint.

This means that you need to decode your data in your client. And this is where the reason-decoder package comes in!

reason-decoder package

reason-decoder is a package for Javascript/Typescript that handles the decoding of your RΞASON’s streamed data.

If you are using React as your client, we recommend checking out our React library.

Here’s how to use it:

An example of using reason-decoder
import Decoder from 'reason-decoder'
// 👆 Importing the Decoder

const decoder = new Decoder()
// 👆 Set up the decoder

for await (const streamedData of makeReasonStreamRequest()) {
  /* 👆 Somehow make a HTTP request to RΞASON and
    get its raw streaming response */

  const yourDecodedObject = decoder.decode(streamedData)
  // 👆 Decode the data!
}

Note that this does not handle making the HTTP request. reason-decoder only handles the decoding of the data.

A complete example

Here’s an example of how you could make a HTTP request to RΞASON and decode it:

An end-to-end example
import Decoder from 'reason-decoder'

async function* getReasonData() {
  const decoder = new Decoder()

  const res = await fetch('http://localhost:1704/your-entrypoint', {
    method: 'GET'
  })

  if (!res.ok) throw new Error('Request failed')

  const stream = res.body
  if (!stream) throw new Error('No stream')

  const reader = stream.getReader()
  let result = await reader.read()
  while (!result.done) {
    const { value } = result

    const text = new TextDecoder('utf-8').decode(value)
    yield decoder.decode(text)

    result = await reader.read()
  }
}

async function main() {
  for await (const data of getReasonData()) {
    console.log(data)
  }
}

main()