feat: use new middleware script
Some checks reported errors
continuous-integration/drone/push Build encountered an error

This commit is contained in:
Kieran 2024-01-11 11:13:29 +00:00
parent 721edb6527
commit 0eb9c56442
Signed by: Kieran
GPG Key ID: DE71CEB3925BE941
2 changed files with 51 additions and 37 deletions

View File

@ -1,37 +0,0 @@
interface Env {}
export const onRequest: PagesFunction<Env> = async context => {
const id = context.params.id as string | undefined;
const prefixes = ["npub1", "nprofile1", "naddr1", "nevent1", "note1"];
const next = await context.next();
if (id && prefixes.some(a => id.startsWith(a))) {
try {
const rsp = await fetch(
`http://nostr.api.v0l.io/api/v1/opengraph/${id}?canonical=${encodeURIComponent("https://zap.stream/%s")}`,
{
method: "POST",
body: await next.arrayBuffer(),
headers: {
"user-agent": "zap.stream/1.0 (https://zap.stream)",
"content-type": "text/html",
accept: "text/html",
},
}
);
if (rsp.ok) {
const body = await rsp.text();
if (body.length > 0) {
return new Response(body, {
headers: {
"content-type": "text/html",
},
});
}
}
} catch {
// ignore
}
}
return next;
};

51
functions/_middleware.ts Normal file
View File

@ -0,0 +1,51 @@
interface Env {}
const HOST = "zap.stream";
export const onRequest: PagesFunction<Env> = async context => {
const u = new URL(context.request.url);
const prefixes = ["npub1", "nprofile1", "naddr1", "nevent1", "note1"];
const isEntityPath = prefixes.some(
a => u.pathname.startsWith(`/${a}`) || u.pathname.startsWith(`/e/${a}`) || u.pathname.startsWith(`/p/${a}`)
);
const nostrAddress = u.pathname.match(/^\/([a-zA-Z0-9_]+)$/i);
const next = await context.next();
if (u.pathname != "/" && (isEntityPath || nostrAddress)) {
//console.log("Handeling path: ", u.pathname, isEntityPath, nostrAddress[1]);
try {
let id = u.pathname.split("/").at(-1);
if (!isEntityPath && nostrAddress) {
id = `${id}@${HOST}`;
}
const fetchApi = `https://nostr.api.v0l.io/api/v1/opengraph/${id}?canonical=${encodeURIComponent(
`https://${HOST}/%s`
)}`;
console.log("Fetching tags from: ", fetchApi);
const reqBuf = await next.arrayBuffer();
const rsp = await fetch(fetchApi, {
method: "POST",
body: reqBuf,
headers: {
"user-agent": `SnortFunctions/1.0 (https://${HOST})`,
"content-type": "text/html",
accept: "text/html",
},
});
if (rsp.ok) {
const body = await rsp.text();
if (body.length > 0) {
return new Response(body, {
headers: {
...Object.fromEntries(rsp.headers.entries()),
"cache-control": "public, max-age=60",
},
});
}
}
} catch (e) {
console.error(e);
}
}
return next;
};