This repository has been archived by the owner on Mar 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
103 lines (90 loc) · 2.27 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import {
DOMParser,
HTMLDocument,
} from "https://deno.land/x/[email protected]/deno-dom-wasm.ts";
async function handler(_request: Request): Promise<Response> {
const urlRequest = new URL(_request.url);
const url = urlRequest.searchParams.get("url");
const filterType = urlRequest.searchParams.get("filter-type");
const fitler = urlRequest.searchParams.get("filter");
if (!url || !filterType || !fitler) {
return new Response(
JSON.stringify({
error: "Please provide the required search parameters",
}),
{
status: 400,
}
);
}
let dom: HTMLDocument | null;
try {
const rawData = await fetch(url);
const data = await rawData.text();
dom = new DOMParser().parseFromString(data, "text/html");
if (!dom) {
return new Response(
JSON.stringify({
error: "The url provided is not valid",
}),
{
status: 400,
}
);
}
} catch {
return new Response(
JSON.stringify({
error: "The url provided is not valid",
}),
{
status: 400,
}
);
}
switch (filterType) {
case "id": {
const scraps = dom.getElementById(fitler)?.textContent;
return new Response(JSON.stringify(scraps), {
status: 200,
headers: {
"content-type": "application/json",
},
});
}
case "class": {
const scraps = dom
.getElementsByClassName(fitler)
.map((e) => e.textContent);
return new Response(JSON.stringify(scraps), {
status: 200,
headers: {
"content-type": "application/json",
},
});
}
case "tag": {
const scraps = dom.getElementsByTagName(fitler).map((e) => e.textContent);
return new Response(JSON.stringify(scraps), {
status: 200,
headers: {
"content-type": "application/json",
},
});
}
default:
return new Response(
JSON.stringify({
error: "The filter type provided is not valid",
}),
{
status: 200,
headers: {
"content-type": "application/json",
},
}
);
}
}
serve(handler);