Skip to content

Commit 58ed779

Browse files
committed
Setup repo redirect function
1 parent 1c08587 commit 58ed779

File tree

5 files changed

+53
-0
lines changed

5 files changed

+53
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
Cargo.lock
66
node_modules
77
target
8+
.wrangler
89

910
web/core
1011
web/*.html

_routes.json

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
{
2+
"version": 1,
3+
"include": [
4+
"/*"
5+
],
6+
"exclude": [
7+
"/",
8+
"/*.html",
9+
"/stats",
10+
"/crates",
11+
"/settings",
12+
"/export"
13+
]
14+
}

functions/repo/[crate].js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
export async function onRequestGet(context) {
2+
let crate = context.params.crate;
3+
let response = await fetch(`https://crates.io/api/v1/crates/${crate}`, {
4+
headers: {
5+
"User-Agent": "Query.rs on Cloudflare Pages function",
6+
}
7+
});
8+
if (response.status !== 200) {
9+
return new Response(response.statusText, { status: response.status });
10+
}
11+
let data = await response.json();
12+
console.log(data.crate);
13+
if (data.crate) {
14+
return Response.redirect(data.crate.repository || data.crate.homepage, 301);
15+
} else {
16+
const html = `<div>
17+
<p>Sorry, the crate <b>${crate}</b> has no repository url. </p>
18+
<h2 class="redirect">Go to <a href="https://crates.io/crates/${crate}">crates.io/crates/${crate}</a> or <a href="https://docs.rs/${crate}">docs.rs/${crate}</a></h2>
19+
</div>`;
20+
return new Response(html, {
21+
headers: {
22+
"content-type": "text/html;charset=UTF-8",
23+
}
24+
});
25+
}
26+
}

package.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"devDependencies": {
3+
"wrangler": "^3.62.0"
4+
}
5+
}

wrangler.toml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
name = "query-rs"
2+
pages_build_output_dir = "./web/dist"
3+
compatibility_date = "2024-06-28"
4+
5+
[dev]
6+
port = 8080
7+
local_protocol = "http"

0 commit comments

Comments
 (0)