57 lines
1.6 KiB
TypeScript
57 lines
1.6 KiB
TypeScript
/**
|
|
* React Hook for RDF Parsing
|
|
* Wraps parser functions with React lifecycle
|
|
*/
|
|
|
|
import { useState, useCallback } from 'react';
|
|
import { parseNTriples, parseTurtle } from '@/lib/rdf/parser';
|
|
import type { ParserOptions } from '@/lib/rdf/parser';
|
|
import type { GraphData, RdfFormat } from '@/types/rdf';
|
|
|
|
interface UseRdfParserReturn {
|
|
parse: (data: string, format: RdfFormat, options?: ParserOptions) => Promise<GraphData>;
|
|
isLoading: boolean;
|
|
error: Error | null;
|
|
graphData: GraphData | null;
|
|
}
|
|
|
|
export function useRdfParser(): UseRdfParserReturn {
|
|
const [isLoading, setIsLoading] = useState(false);
|
|
const [error, setError] = useState<Error | null>(null);
|
|
const [graphData, setGraphData] = useState<GraphData | null>(null);
|
|
|
|
const parse = useCallback(async (data: string, format: RdfFormat, options?: ParserOptions) => {
|
|
setIsLoading(true);
|
|
setError(null);
|
|
|
|
try {
|
|
let result: GraphData;
|
|
|
|
switch (format) {
|
|
case 'text/turtle':
|
|
result = parseTurtle(data, options);
|
|
break;
|
|
case 'application/n-triples':
|
|
result = parseNTriples(data, options);
|
|
break;
|
|
default:
|
|
throw new Error(`Unsupported format: ${format}`);
|
|
}
|
|
|
|
if (result.error) {
|
|
throw new Error(result.error);
|
|
}
|
|
|
|
setGraphData(result);
|
|
return result;
|
|
} catch (err) {
|
|
const error = err instanceof Error ? err : new Error('Parsing failed');
|
|
setError(error);
|
|
throw error;
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
}, []);
|
|
|
|
return { parse, isLoading, error, graphData };
|
|
}
|