Skip to content

Commit 046db52

Browse files
authored
ReadableStream parse input (#3)
1 parent a3cf385 commit 046db52

File tree

3 files changed

+19
-11
lines changed

3 files changed

+19
-11
lines changed

Diff for: deno.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@dbushell/xml-streamify",
3-
"version": "0.5.0",
3+
"version": "0.6.0",
44
"exports": {
55
".": "./mod.ts",
66
"./node": "./src/node.ts",

Diff for: examples/deno.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ const blog = async () => {
1717

1818
const podcast = async () => {
1919
const contoller = new AbortController();
20-
const parser = parse('https://feed.syntax.fm/rss', {
20+
const response = await fetch('https://feed.syntax.fm/rss');
21+
const parser = parse(response.body!, {
2122
signal: contoller.signal
2223
});
2324
const items: Node[] = [];

Diff for: src/parse.ts

+16-9
Original file line numberDiff line numberDiff line change
@@ -16,29 +16,36 @@ const ignoreTypes: Partial<Record<NodeType, keyof ParseOptions>> = {
1616

1717
/**
1818
* Async generator function for parsing a streamed XML document
19-
* @param url URL to fetch and parse
19+
* @param input URL to fetch and parse (or a ReadableStream)
2020
* @param options Parsing options {@link ParseOptions}
2121
* @returns Yields parsed XML nodes {@link Node}
2222
*/
2323
export async function* parse(
24-
url: string | URL,
24+
input: string | URL | ReadableStream,
2525
options?: ParseOptions
2626
): AsyncGenerator<Node, Node | void, void> {
27-
url = new URL(url);
28-
2927
const document = new Node('@document');
30-
3128
try {
3229
const init = {...options?.fetchOptions};
3330
if (options?.signal) {
3431
init.signal = options.signal;
3532
}
36-
const response = await fetch(url, init);
37-
if (!response.ok || !response.body) {
38-
throw new Error(`Bad response`);
33+
34+
let source: ReadableStream;
35+
36+
// Fetch stream if URL is provided as input
37+
if (typeof input === 'string' || input instanceof URL) {
38+
input = new URL(input);
39+
const response = await fetch(input, init);
40+
if (!response.ok || !response.body) {
41+
throw new Error(`Bad response`);
42+
}
43+
source = response.body;
44+
} else {
45+
source = input;
3946
}
4047

41-
const stream = response.body
48+
const stream = source
4249
.pipeThrough(new TextDecoderStream())
4350
.pipeThrough(new XMLStream(), {
4451
signal: options?.signal

0 commit comments

Comments
 (0)