feat: expose layouts and pages on App (#3086)
This PR extracts the functionality from the `fs_routes` plugin and exposes it onto `App`. These are the new APIs: - `app.layout(pattern, route)` - `app.onError(pattern, route)` - `app.notFound(pattern, route)` - `app.route(pattern, route)` This also removes the need for `.use(staticFiles())`. This line can be safely removed. Fixes https://github.com/denoland/fresh/issues/3040 Fixes https://github.com/denoland/fresh/issues/3033 Fixes https://github.com/denoland/fresh/issues/2591 Fixes https://github.com/denoland/fresh/issues/950 Fixes https://github.com/denoland/fresh/issues/1918
This commit is contained in:
@@ -30,16 +30,10 @@ Deno.test("CORS - Preflight default", async () => {
|
||||
const res = await handler(req);
|
||||
|
||||
expect(res.status).toBe(204);
|
||||
expect(res.statusText).toBe("No Content");
|
||||
expect(res.headers.get("Access-Control-Allow-Methods")?.split(",")[0]).toBe(
|
||||
"GET",
|
||||
);
|
||||
expect(res.headers.get("Access-Control-Allow-Headers")?.split(",")).toEqual(
|
||||
[
|
||||
"X-PINGOTHER",
|
||||
"Content-Type",
|
||||
],
|
||||
);
|
||||
expect(res.headers.get("Access-Control-Allow-Methods")?.split(",")[0])
|
||||
.toBe("GET");
|
||||
expect(res.headers.get("Access-Control-Allow-Headers")?.split(","))
|
||||
.toEqual(["X-PINGOTHER", "Content-Type"]);
|
||||
});
|
||||
|
||||
Deno.test("CORS - Preflight with options", async () => {
|
||||
|
||||
+23
-21
@@ -1,4 +1,4 @@
|
||||
import type { FreshContext, FreshReqContext } from "../context.ts";
|
||||
import { type Context, getInternals } from "../context.ts";
|
||||
import type { App as _App } from "../app.ts";
|
||||
import type { Define as _Define } from "../define.ts";
|
||||
|
||||
@@ -6,14 +6,14 @@ import type { Define as _Define } from "../define.ts";
|
||||
* A middleware function is the basic building block of Fresh. It allows you
|
||||
* to respond to an incoming request in any way you want. You can redirect
|
||||
* routes, serve files, create APIs and much more. Middlewares can be chained by
|
||||
* calling {@linkcode FreshContext.next|ctx.next()} inside of the function.
|
||||
* calling {@linkcode Context.next|ctx.next()} inside of the function.
|
||||
*
|
||||
* Middlewares can be synchronous or asynchronous. If a middleware returns a
|
||||
* {@linkcode Response} object, the response will be sent back to the client. If
|
||||
* a middleware returns a `Promise<Response>`, Fresh will wait for the promise
|
||||
* to resolve before sending the response.
|
||||
*
|
||||
* A {@linkcode FreshContext} object is passed to the middleware function. This
|
||||
* A {@linkcode Context} object is passed to the middleware function. This
|
||||
* object contains the original request object, as well as any state related to
|
||||
* the current request. The context object also contains methods to redirect
|
||||
* the client to another URL, or to call the next middleware in the chain.
|
||||
@@ -72,7 +72,7 @@ import type { Define as _Define } from "../define.ts";
|
||||
* ```
|
||||
*/
|
||||
export type MiddlewareFn<State> = (
|
||||
ctx: FreshContext<State>,
|
||||
ctx: Context<State>,
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
/**
|
||||
@@ -82,27 +82,29 @@ export type MiddlewareFn<State> = (
|
||||
export type Middleware<State> = MiddlewareFn<State> | MiddlewareFn<State>[];
|
||||
|
||||
export function runMiddlewares<State>(
|
||||
middlewares: MiddlewareFn<State>[][],
|
||||
ctx: FreshReqContext<State>,
|
||||
middlewares: MiddlewareFn<State>[],
|
||||
ctx: Context<State>,
|
||||
): Promise<Response> {
|
||||
let fn = ctx.next;
|
||||
let i = middlewares.length;
|
||||
while (i--) {
|
||||
const stack = middlewares[i];
|
||||
let j = stack.length;
|
||||
while (j--) {
|
||||
const local = fn;
|
||||
const next = stack[j];
|
||||
fn = async () => {
|
||||
ctx.next = local;
|
||||
try {
|
||||
return await next(ctx);
|
||||
} catch (err) {
|
||||
ctx.error = err;
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
}
|
||||
const local = fn;
|
||||
const next = middlewares[i];
|
||||
fn = async () => {
|
||||
const internals = getInternals(ctx);
|
||||
const { app: prevApp, layouts: prevLayouts } = internals;
|
||||
|
||||
ctx.next = local;
|
||||
try {
|
||||
return await next(ctx);
|
||||
} catch (err) {
|
||||
ctx.error = err;
|
||||
throw err;
|
||||
} finally {
|
||||
internals.app = prevApp;
|
||||
internals.layouts = prevLayouts;
|
||||
}
|
||||
};
|
||||
}
|
||||
return fn();
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ Deno.test("runMiddleware", async () => {
|
||||
];
|
||||
|
||||
const server = serveMiddleware<{ text: string }>((ctx) =>
|
||||
runMiddlewares([middlewares], ctx)
|
||||
runMiddlewares(middlewares, ctx)
|
||||
);
|
||||
|
||||
const res = await server.get("/");
|
||||
@@ -43,7 +43,7 @@ Deno.test("runMiddleware - middlewares should only be called once", async () =>
|
||||
|
||||
const server = serveMiddleware<{ count: number }>((ctx) =>
|
||||
runMiddlewares(
|
||||
[[A, (ctx) => new Response(String(ctx.state.count))]],
|
||||
[A, (ctx) => new Response(String(ctx.state.count))],
|
||||
ctx,
|
||||
)
|
||||
);
|
||||
@@ -75,8 +75,11 @@ Deno.test("runMiddleware - runs multiple stacks", async () => {
|
||||
ctx.state.text = "";
|
||||
return runMiddlewares(
|
||||
[
|
||||
[A, B],
|
||||
[C, D, (ctx) => new Response(String(ctx.state.text))],
|
||||
A,
|
||||
B,
|
||||
C,
|
||||
D,
|
||||
(ctx) => new Response(String(ctx.state.text)),
|
||||
],
|
||||
ctx,
|
||||
);
|
||||
@@ -122,7 +125,7 @@ Deno.test("runMiddleware - throws errors", async () => {
|
||||
];
|
||||
|
||||
const server = serveMiddleware<{ text: string }>((ctx) =>
|
||||
runMiddlewares([middlewares], ctx)
|
||||
runMiddlewares(middlewares, ctx)
|
||||
);
|
||||
|
||||
try {
|
||||
|
||||
@@ -3,8 +3,8 @@ import { contentType as getContentType } from "@std/media-types/content-type";
|
||||
import type { MiddlewareFn } from "./mod.ts";
|
||||
import { ASSET_CACHE_BUST_KEY } from "../runtime/shared_internal.tsx";
|
||||
import { BUILD_ID } from "../runtime/build_id.ts";
|
||||
import { tracer } from "../otel.ts";
|
||||
import { getBuildCache } from "../context.ts";
|
||||
import { trace, tracer } from "../otel.ts";
|
||||
|
||||
/**
|
||||
* Fresh middleware to enable file-system based routing.
|
||||
@@ -12,11 +12,20 @@ import { trace, tracer } from "../otel.ts";
|
||||
* // Enable Fresh static file serving
|
||||
* app.use(staticFiles());
|
||||
* ```
|
||||
* @deprecated This is not needed anymore. Remove this middleware.
|
||||
*/
|
||||
export function staticFiles<T>(): MiddlewareFn<T> {
|
||||
return async function freshStaticFiles(ctx) {
|
||||
return await ctx.next();
|
||||
};
|
||||
}
|
||||
|
||||
export function serveInternalStaticFiles<T>(): MiddlewareFn<T> {
|
||||
return async function freshServeStaticFiles(ctx) {
|
||||
const { req, url, config } = ctx;
|
||||
|
||||
const buildCache = getBuildCache(ctx);
|
||||
if (buildCache === null) return await ctx.next();
|
||||
|
||||
let pathname = decodeURIComponent(url.pathname);
|
||||
if (config.basePath) {
|
||||
@@ -33,7 +42,7 @@ export function staticFiles<T>(): MiddlewareFn<T> {
|
||||
if (pathname === "/favicon.ico") {
|
||||
return new Response(null, { status: 404 });
|
||||
}
|
||||
return ctx.next();
|
||||
return await ctx.next();
|
||||
}
|
||||
|
||||
if (req.method !== "GET" && req.method !== "HEAD") {
|
||||
@@ -41,12 +50,6 @@ export function staticFiles<T>(): MiddlewareFn<T> {
|
||||
return new Response("Method Not Allowed", { status: 405 });
|
||||
}
|
||||
|
||||
const parentSpan = trace.getActiveSpan();
|
||||
if (parentSpan) {
|
||||
parentSpan.updateName(`${req.method} /*`);
|
||||
parentSpan.setAttribute("http.route", "/*");
|
||||
}
|
||||
|
||||
const span = tracer.startSpan("static file", {
|
||||
attributes: { "fresh.span_type": "static_file" },
|
||||
startTime,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { staticFiles } from "./static_files.ts";
|
||||
import { serveInternalStaticFiles } from "./static_files.ts";
|
||||
import { serveMiddleware } from "../test_utils.ts";
|
||||
import type { BuildCache, StaticFile } from "../build_cache.ts";
|
||||
import { expect } from "@std/expect";
|
||||
@@ -39,7 +39,7 @@ Deno.test("static files - 200", async () => {
|
||||
"foo.css": { content: "body {}", hash: null },
|
||||
});
|
||||
const server = serveMiddleware(
|
||||
staticFiles(),
|
||||
serveInternalStaticFiles(),
|
||||
{ buildCache },
|
||||
);
|
||||
|
||||
@@ -59,7 +59,7 @@ Deno.test("static files - HEAD 200", async () => {
|
||||
"foo.css": { content: "body {}", hash: null },
|
||||
});
|
||||
const server = serveMiddleware(
|
||||
staticFiles(),
|
||||
serveInternalStaticFiles(),
|
||||
{ buildCache },
|
||||
);
|
||||
|
||||
@@ -76,7 +76,7 @@ Deno.test("static files - etag", async () => {
|
||||
"foo.css": { content: "body {}", hash: "123" },
|
||||
});
|
||||
const server = serveMiddleware(
|
||||
staticFiles(),
|
||||
serveInternalStaticFiles(),
|
||||
{ buildCache },
|
||||
);
|
||||
|
||||
@@ -101,7 +101,7 @@ Deno.test("static files - etag", async () => {
|
||||
Deno.test("static files - 404 on missing favicon.ico", async () => {
|
||||
const buildCache = new MockBuildCache({});
|
||||
const server = serveMiddleware(
|
||||
staticFiles(),
|
||||
serveInternalStaticFiles(),
|
||||
{ buildCache },
|
||||
);
|
||||
const res = await server.get("favicon.ico");
|
||||
@@ -114,7 +114,7 @@ Deno.test("static files - 405 on wrong HTTP method", async () => {
|
||||
"foo.css": { content: "body {}", hash: null },
|
||||
});
|
||||
const server = serveMiddleware(
|
||||
staticFiles(),
|
||||
serveInternalStaticFiles(),
|
||||
{ buildCache },
|
||||
);
|
||||
|
||||
@@ -131,7 +131,7 @@ Deno.test("static files - disables caching in development", async () => {
|
||||
"foo.css": { content: "body {}", hash: null },
|
||||
});
|
||||
const server = serveMiddleware(
|
||||
staticFiles(),
|
||||
serveInternalStaticFiles(),
|
||||
{
|
||||
buildCache,
|
||||
config: {
|
||||
@@ -159,7 +159,7 @@ Deno.test("static files - enables caching in production", async () => {
|
||||
"foo.css": { content: "body {}", hash: null },
|
||||
});
|
||||
const server = serveMiddleware(
|
||||
staticFiles(),
|
||||
serveInternalStaticFiles(),
|
||||
{
|
||||
buildCache,
|
||||
config: {
|
||||
@@ -189,7 +189,7 @@ Deno.test("static files - decoded pathname", async () => {
|
||||
"인천.avif": { content: "body {}", hash: null },
|
||||
});
|
||||
const server = serveMiddleware(
|
||||
staticFiles(),
|
||||
serveInternalStaticFiles(),
|
||||
{ buildCache },
|
||||
);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user