|
| 1 | +import { useEffect, useState } from 'react' |
| 2 | +import type { FileSource } from '../../lib/sources/types.js' |
| 3 | +import { parseFileSize } from '../../lib/utils.js' |
| 4 | +import styles from '../../styles/Json.module.css' |
| 5 | +import Json from '../Json.js' |
| 6 | +import { Spinner } from '../Layout.js' |
| 7 | +import ContentHeader, { ContentSize } from './ContentHeader.js' |
| 8 | +import { avroData, avroMetadata } from 'icebird' |
| 9 | + |
| 10 | +interface ViewerProps { |
| 11 | + source: FileSource |
| 12 | + setError: (error: Error | undefined) => void |
| 13 | +} |
| 14 | + |
| 15 | +/** |
| 16 | + * Apache Avro viewer component. |
| 17 | + */ |
| 18 | +export default function AvroView({ source, setError }: ViewerProps) { |
| 19 | + const [content, setContent] = useState<ContentSize>() |
| 20 | + const [json, setJson] = useState<unknown>() |
| 21 | + const [isLoading, setIsLoading] = useState(true) |
| 22 | + |
| 23 | + const { resolveUrl, requestInit } = source |
| 24 | + |
| 25 | + // Load avro content as json |
| 26 | + useEffect(() => { |
| 27 | + async function loadContent() { |
| 28 | + try { |
| 29 | + setIsLoading(true) |
| 30 | + const res = await fetch(resolveUrl, requestInit) |
| 31 | + if (res.status === 401) { |
| 32 | + const text = await res.text() |
| 33 | + setError(new Error(text)) |
| 34 | + setContent(undefined) |
| 35 | + return |
| 36 | + } |
| 37 | + // Parse avro file |
| 38 | + const buffer = await res.arrayBuffer() |
| 39 | + const fileSize = parseFileSize(res.headers) ?? buffer.byteLength |
| 40 | + const reader = { view: new DataView(buffer), offset: 0 } |
| 41 | + const { metadata, syncMarker } = avroMetadata(reader) |
| 42 | + const json = avroData({ reader, metadata, syncMarker }) |
| 43 | + setError(undefined) |
| 44 | + setContent({ fileSize }) |
| 45 | + setJson(json) |
| 46 | + } catch (error) { |
| 47 | + setError(error as Error) |
| 48 | + } finally { |
| 49 | + setIsLoading(false) |
| 50 | + } |
| 51 | + } |
| 52 | + void loadContent() |
| 53 | + }, [resolveUrl, requestInit, setError]) |
| 54 | + |
| 55 | + const headers = content === undefined && <span>Loading...</span> |
| 56 | + |
| 57 | + return <ContentHeader content={content} headers={headers}> |
| 58 | + <code className={styles.jsonView}> |
| 59 | + <Json json={json} /> |
| 60 | + </code> |
| 61 | + |
| 62 | + {isLoading && <div className='center'><Spinner /></div>} |
| 63 | + </ContentHeader> |
| 64 | +} |
0 commit comments