JSONStream
ENHANCE
USER EXPERIENCE
Vihang Patel
Senior Developer - Frontend @BookMyShow
What is JSONStream ?
JSONStream
JSON stream is basically a continuous stream of
JSON object chunk which is sent over the wire.
What problem it solves ?
How it
Works ?
RESPONSE SHOULD BE CHUNKED
BY DEFAULT CHUNK SIZE IS 64K
BROWSER SUPPORT
Demo build in
Comparison
With streaming : First render was quick,
Without streaming : It took ~1.2s for first render on high end
devices
BACKEND CHANGES
Response
Chunk
Chunk
Chunk
Chunk
Chunk
Chunk
Chunk
Chunk
Chunk
Chunk
Chunk
Chunk
Chunk
Step 1
JSON response should be divided in meaningful chunk
let stringData = []
for (let c = 0; c < data.length; c++) {
const temp = JSON.stringify(data[c])
const arr = chunkify(temp)
stringData = [...stringData, ...arr]
}
function chunkify(data) {
const dataArr = []
if (data.length > SIZE) {
dataArr.push(data.substr(0, SIZE))
return [...dataArr, ...chunkify(data.substr(SIZE, data.length))]
} else {
return [data]
}
}
50K
10K
25K
30K
64K
3K
20K
25K
43K
12K
55K
23K
Chunk
Chunk
Chunk
Chunk
Chunk
Chunk
Chunk
Chunk
Chunk
Chunk
Chunk
app.get("/stream-api", function(req, res) {
for (let c = 0; c < chunkedData.length; c++) {
setTimeout(() => {
res.write(chunkedData[c])
res.flush()
if (c == chunkedData.length - 1) {
res.end()
}
}, c * 50)
}
})
Step 2
Each venue will become chunk and will be streamed over the wire
CLIENT CHANGES
Client Changes
fetch(urlToLoad).then(response => {
const reader = response.body.getReader()
}
fetch(urlToLoad).then(response => {
const reader = response.body.getReader()
const stream = new ReadableStream({�
� })
}
fetch(urlToLoad).then(response => {
const reader = response.body.getReader()
const stream = new ReadableStream({� // read untill last chunk is encountered
start(controller) {
} � })
}
fetch(urlToLoad).then(response => {
const reader = response.body.getReader()
const stream = new ReadableStream({� // read untill last chunk is encountered
start(controller) {
function push() {
// "done" is a Boolean and value a "Uint8Array"
}
} � })
}
fetch(urlToLoad).then(response => {
const reader = response.body.getReader()
const stream = new ReadableStream({� // read untill last chunk is encountered
start(controller) {
function push() {
// "done" is a Boolean and value a "Uint8Array"
return reader.read().then(({done, value}) => {
// "done" is a Boolean and value a "Uint8Array"})
.then(({done}) => {
if (!done) {
push()
}
})
}
}
} � })
}
CHALLENGES
Challenges
Libraries
Thank you