Skip to content

Commit

Permalink
ReadableStream parse input (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
dbushell authored Jul 26, 2024
1 parent a3cf385 commit 046db52
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 11 deletions.
2 changes: 1 addition & 1 deletion deno.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@dbushell/xml-streamify",
"version": "0.5.0",
"version": "0.6.0",
"exports": {
".": "./mod.ts",
"./node": "./src/node.ts",
Expand Down
3 changes: 2 additions & 1 deletion examples/deno.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ const blog = async () => {

const podcast = async () => {
const contoller = new AbortController();
const parser = parse('https://feed.syntax.fm/rss', {
const response = await fetch('https://feed.syntax.fm/rss');
const parser = parse(response.body!, {
signal: contoller.signal
});
const items: Node[] = [];
Expand Down
25 changes: 16 additions & 9 deletions src/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,29 +16,36 @@ const ignoreTypes: Partial<Record<NodeType, keyof ParseOptions>> = {

/**
* Async generator function for parsing a streamed XML document
* @param url URL to fetch and parse
* @param input URL to fetch and parse (or a ReadableStream)
* @param options Parsing options {@link ParseOptions}
* @returns Yields parsed XML nodes {@link Node}
*/
export async function* parse(
url: string | URL,
input: string | URL | ReadableStream,
options?: ParseOptions
): AsyncGenerator<Node, Node | void, void> {
url = new URL(url);

const document = new Node('@document');

try {
const init = {...options?.fetchOptions};
if (options?.signal) {
init.signal = options.signal;
}
const response = await fetch(url, init);
if (!response.ok || !response.body) {
throw new Error(`Bad response`);

let source: ReadableStream;

// Fetch stream if URL is provided as input
if (typeof input === 'string' || input instanceof URL) {
input = new URL(input);
const response = await fetch(input, init);
if (!response.ok || !response.body) {
throw new Error(`Bad response`);
}
source = response.body;
} else {
source = input;
}

const stream = response.body
const stream = source
.pipeThrough(new TextDecoderStream())
.pipeThrough(new XMLStream(), {
signal: options?.signal
Expand Down

0 comments on commit 046db52

Please sign in to comment.