Last active
May 10, 2024 19:29
-
-
Save bartkl/7884669d6eda3813d3f4b9075f7c3a0b to your computer and use it in GitHub Desktop.
Streaming JSON chunks (FastAPI <-> fetchAPI)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# FastAPI. | |
async def stream_json_list(items): | |
for item in items: | |
yield item | |
await asyncio.sleep(4.0) # To demonstrate, visibly, the successful implementation. | |
async def get_media_metadata(tags: Optional[Set[str]] = Query(None, | |
description="Tags to filter on")): | |
metadata = metadata_repository.get_metadata_for_items_by_tags(tags=tags) | |
return StreamingResponse( | |
stream_json_list(m.json() for m in metadata), | |
media_type='application/json' | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async performSearch () { | |
const utf8decoder = new TextDecoder() | |
this.getMediaMetadataByTags() | |
.then(response => { | |
const stream = new ReadableStream({ | |
start (controller) { | |
const reader = response.body.getReader() | |
read() | |
function read () { | |
reader.read().then(({ done, value }) => { | |
if (done) { | |
controller.close() | |
return null | |
} | |
const textValue = utf8decoder.decode(value) | |
console.log(textValue) | |
// this.items += textValue | |
controller.enqueue(value) | |
read() | |
}) | |
} | |
} | |
}) | |
return new Response(stream, { headers: { 'content-type': 'application/json' } }) | |
}) | |
async getMediaMetadataByTags () { | |
const response = await fetch(`http://localhost:8080/api/v1/media/metadata/?tags=${this.searchTerm}`) | |
return await response.json() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment