Skip to content

Commit

Permalink
Initialize middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
rojvv committed Mar 20, 2024
1 parent 8da9418 commit 9e41624
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
2 changes: 2 additions & 0 deletions fresh.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import * as $_404 from "./routes/_404.tsx";
import * as $_app from "./routes/_app.tsx";
import * as $_middleware from "./routes/_middleware.tsx";
import * as $connectivity_test from "./routes/connectivity-test.tsx";
import * as $file_id_analyzer from "./routes/file-id-analyzer.tsx";
import * as $filter_query_browser from "./routes/filter-query-browser.tsx";
Expand Down Expand Up @@ -32,6 +33,7 @@ const manifest = {
routes: {
"./routes/_404.tsx": $_404,
"./routes/_app.tsx": $_app,
"./routes/_middleware.tsx": $_middleware,
"./routes/connectivity-test.tsx": $connectivity_test,
"./routes/file-id-analyzer.tsx": $file_id_analyzer,
"./routes/filter-query-browser.tsx": $filter_query_browser,
Expand Down
47 changes: 47 additions & 0 deletions routes/_middleware.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { FreshContext } from "$fresh/server.ts";

const HEADER = new TextEncoder().encode("<!--- See something wrong? Let us know in our chat: https://t.me/grammyjs --->");

export async function handler(req: Request, ctx: FreshContext) {
try {
const res = await ctx.next();
if (
res.body != null &&
res.status == 200 &&
res.headers.get("content-type")?.includes("text/html")
) {
const reader = res.body.getReader();
let headerSent = false;
const rs = new ReadableStream({
async pull(controller) {
const result = await reader.read();
if (result?.done) {
controller.close();
} else if (result?.value) {
if (!headerSent) {
headerSent = true;
controller.enqueue(HEADER);
return;
}
controller.enqueue(result.value);
} else if (!result) {
controller.error();
}
},
async cancel(reason) {
try {
await res.body?.cancel(reason);
} catch {
//
}
},
});
return new Response(rs, { headers: res.headers, status: res.status });
} else {
return res;
}
} catch (err) {
console.trace(err);
}
return Response.redirect(new URL("/", req.url));
}

0 comments on commit 9e41624

Please sign in to comment.