fix: remove Data from FreshContext (#2473)

This is now only on `PageProps`.
This commit is contained in:
Luca Casonato
2024-05-31 13:50:28 +02:00
committed by GitHub
parent dc283a137b
commit 8d85945da6
16 changed files with 131 additions and 124 deletions
+2 -5
View File
@@ -205,21 +205,18 @@ export class App<State> {
const { params, handlers } = matched;
const ctx = new FreshReqContext<State>(
req,
conn,
params,
this.config,
next,
this.#islandRegistry,
this.#buildCache!,
conn,
);
ctx.params = params;
try {
if (handlers.length === 1 && handlers[0].length === 1) {
return handlers[0][0](ctx);
}
ctx.next = next;
return await runMiddlewares(handlers, ctx);
} catch (err) {
if (err instanceof HttpError) {
+8 -14
View File
@@ -5,31 +5,25 @@ import type { HandlerByMethod } from "../handlers.ts";
/**
* @deprecated Use {@link FreshContext} instead
*/
export type AppProps<Data = unknown, T = unknown> = FreshContext<Data, T>;
export type AppProps<_Data = unknown, T = unknown> = FreshContext<T>;
/**
* @deprecated Use {@link FreshContext} instead
*/
export type LayoutProps<Data = unknown, T = unknown> = FreshContext<Data, T>;
export type LayoutProps<_Data = unknown, T = unknown> = FreshContext<T>;
/**
* @deprecated Use {@link FreshContext} instead
*/
export type UnknownPageProps<Data = unknown, T = unknown> = FreshContext<
Data,
T
>;
export type UnknownPageProps<_Data = unknown, T = unknown> = FreshContext<T>;
/**
* @deprecated Use {@link FreshContext} instead
*/
export type ErrorPageProps<Data = unknown, T = unknown> = FreshContext<Data, T>;
export type ErrorPageProps<_Data = unknown, T = unknown> = FreshContext<T>;
/**
* @deprecated Use {@link FreshContext} instead
*/
// deno-lint-ignore no-explicit-any
export type RouteContext<T = any, S = Record<string, unknown>> = FreshContext<
T,
S
>;
export type RouteContext<_T = never, S = Record<string, unknown>> =
FreshContext<S>;
// deno-lint-ignore no-explicit-any
export type Handlers<T = any, State = Record<string, unknown>> =
@@ -37,10 +31,10 @@ export type Handlers<T = any, State = Record<string, unknown>> =
function defineFn<State>(
fn: (
ctx: FreshContext<unknown, State>,
ctx: FreshContext<State>,
) => Request | VNode | null | Promise<Request | VNode | null>,
): (
ctx: FreshContext<unknown, State>,
ctx: FreshContext<State>,
) => Request | VNode | null | Promise<Request | VNode | null> {
return fn;
}
+1 -1
View File
@@ -1,5 +1,5 @@
import * as path from "@std/path";
import { MODE, type Mode } from "./runtime/server/mod.tsx";
import { MODE, type Mode } from "./runtime/server/mod.ts";
export interface FreshPlugin {
name: string;
+59 -22
View File
@@ -1,6 +1,12 @@
import { type ComponentType, h, isValidElement, type VNode } from "preact";
import type { ResolvedFreshConfig } from "./config.ts";
import {
type ComponentType,
type FunctionComponent,
h,
isValidElement,
type VNode,
} from "preact";
import { renderToString } from "preact-render-to-string";
import type { ResolvedFreshConfig } from "./config.ts";
import type { BuildCache } from "./build_cache.ts";
import {
FreshScripts,
@@ -21,22 +27,21 @@ export type ServerIslandRegistry = Map<ComponentType, Island>;
/**
* The context passed to every middleware. It is unique for every request.
*/
export interface FreshContext<Data = unknown, State = unknown> {
export interface FreshContext<State = unknown> {
/** Reference to the resolved Fresh configuration */
readonly config: ResolvedFreshConfig;
state: State;
data: Data;
readonly state: State;
/** The original incoming `Request` object` */
req: Request;
readonly req: Request;
/**
* The request url parsed into an `URL` instance. This is typically used
* to apply logic based on the pathname of the incoming url or when
* certain search parameters are set.
*/
url: URL;
params: Record<string, string>;
error: unknown;
info?: Deno.ServeHandlerInfo | Deno.ServeUnixHandlerInfo;
readonly url: URL;
readonly params: Record<string, string>;
readonly error: unknown;
readonly info: Deno.ServeHandlerInfo | Deno.ServeUnixHandlerInfo;
/**
* Return a redirect response to the specified path. This is the
* preferred way to do redirects in Fresh.
@@ -78,32 +83,48 @@ export interface FreshContext<Data = unknown, State = unknown> {
render(vnode: VNode, init?: ResponseInit): Response | Promise<Response>;
}
export let getBuildCache: (ctx: FreshContext<unknown, unknown>) => BuildCache;
export let getBuildCache: (ctx: FreshContext<unknown>) => BuildCache;
export class FreshReqContext<State> implements FreshContext<unknown, State> {
export class FreshReqContext<State>
implements FreshContext<State>, PageProps<unknown, State> {
config: ResolvedFreshConfig;
url: URL;
params = {} as Record<string, string>;
state = {} as State;
data = {} as never;
error: Error | null = null;
req: Request;
params: Record<string, string>;
state: State = {} as State;
data: unknown = undefined;
error: unknown | null = null;
info: Deno.ServeHandlerInfo | Deno.ServeUnixHandlerInfo;
next: FreshContext<State>["next"];
#islandRegistry: ServerIslandRegistry;
#buildCache: BuildCache;
// FIXME: remove after switching to <Slot />
Component!: FunctionComponent;
static {
getBuildCache = (ctx) => (ctx as FreshReqContext<unknown>).#buildCache;
}
constructor(
public req: Request,
public config: ResolvedFreshConfig,
public next: FreshContext<unknown, State>["next"],
req: Request,
info: Deno.ServeHandlerInfo | Deno.ServeUnixHandlerInfo,
params: Record<string, string>,
config: ResolvedFreshConfig,
next: FreshContext<State>["next"],
islandRegistry: ServerIslandRegistry,
buildCache: BuildCache,
public info: Deno.ServeHandlerInfo | Deno.ServeUnixHandlerInfo,
) {
this.url = new URL(req.url);
this.req = req;
this.info = info;
this.params = params;
this.config = config;
this.next = next;
this.#islandRegistry = islandRegistry;
this.#buildCache = buildCache;
this.url = new URL(req.url);
}
redirect(pathOrUrl: string, status = 302): Response {
@@ -168,9 +189,21 @@ export class FreshReqContext<State> implements FreshContext<unknown, State> {
}
}
Object.defineProperties(FreshReqContext.prototype, {
config: { enumerable: true },
url: { enumerable: true },
req: { enumerable: true },
params: { enumerable: true },
state: { enumerable: true },
data: { enumerable: true },
error: { enumerable: true },
next: { enumerable: true },
info: { enumerable: true },
});
function preactRender<State, Data>(
vnode: VNode,
ctx: FreshContext<Data, State>,
ctx: PageProps<Data, State>,
islandRegistry: ServerIslandRegistry,
buildCache: BuildCache,
partialId: string,
@@ -201,3 +234,7 @@ function preactRender<State, Data>(
setRenderState(null);
}
}
export type PageProps<Data = unknown, T = unknown> =
& Omit<FreshContext<T>, "next" | "render" | "redirect">
& { data: Data; Component: FunctionComponent };
+4 -10
View File
@@ -1,7 +1,7 @@
import type { AnyComponent } from "preact";
import type { HandlerByMethod, RouteHandler } from "./handlers.ts";
import type { FreshContext } from "./context.ts";
import type { Middleware } from "./middlewares/mod.ts";
import type { PageProps } from "./context.ts";
/**
* A set of define functions that enable better type inference and code
@@ -57,9 +57,7 @@ export interface Define<State> {
handlers<
Data,
Handlers extends RouteHandler<Data, State> = RouteHandler<Data, State>,
>(
handlers: Handlers,
): typeof handlers;
>(handlers: Handlers): typeof handlers;
/**
* Define a page component that will be rendered when a route handler returns
@@ -110,9 +108,7 @@ export interface Define<State> {
// deno-lint-ignore no-explicit-any
Handler extends RouteHandler<any, State> = never,
Data = Handler extends HandlerByMethod<infer Data, State> ? Data : never,
>(
render: AnyComponent<FreshContext<Data, State> & { Component: () => null }>,
): typeof render;
>(render: AnyComponent<PageProps<Data, State>>): typeof render;
/**
* Define a {@link Middleware} that will be used to process requests before
@@ -135,9 +131,7 @@ export interface Define<State> {
*
* @typeParam M The type of the middleware function. This will be inferred from the input function. Do not manually specify this type.
*/
middleware<M extends Middleware<State>>(
middleware: M,
): typeof middleware;
middleware<M extends Middleware<State>>(middleware: M): typeof middleware;
}
/**
+1 -1
View File
@@ -1,4 +1,4 @@
import { setMode } from "../runtime/server/mod.tsx";
import { setMode } from "../runtime/server/mod.ts";
export { Builder, type FreshBuilder } from "./builder.ts";
export {
+1 -1
View File
@@ -192,7 +192,7 @@ export function isHandlerByMethod<D, S>(
* ```
*/
export interface HandlerFn<Data, State> {
(ctx: FreshContext<Data, State>):
(ctx: FreshContext<State>):
| Response
| PageResponse<Data>
| Promise<Response | PageResponse<Data>>;
+3 -3
View File
@@ -1,4 +1,4 @@
import type { FreshContext } from "../context.ts";
import type { FreshContext, FreshReqContext } from "../context.ts";
import type { App as _App } from "../app.ts";
/**
@@ -71,7 +71,7 @@ import type { App as _App } from "../app.ts";
* ```
*/
export type MiddlewareFn<State> = (
ctx: FreshContext<unknown, State>,
ctx: FreshContext<State>,
) => Response | Promise<Response>;
/**
@@ -82,7 +82,7 @@ export type Middleware<State> = MiddlewareFn<State> | MiddlewareFn<State>[];
export function runMiddlewares<State>(
middlewares: MiddlewareFn<State>[][],
ctx: FreshContext<unknown, State>,
ctx: FreshReqContext<State>,
): Promise<Response> {
let fn = ctx.next;
let i = middlewares.length;
+4 -6
View File
@@ -5,9 +5,8 @@ import { serveMiddleware } from "../test_utils.ts";
Deno.test("trailingSlashes - always", async () => {
const middleware = trailingSlashes("always");
const server = serveMiddleware(async (ctx) => {
ctx.next = async () => new Response("ok");
return await middleware(ctx);
const server = serveMiddleware(middleware, {
next: async () => new Response("ok"),
});
let res = await server.get("/");
@@ -33,9 +32,8 @@ Deno.test("trailingSlashes - always", async () => {
Deno.test("trailingSlashes - never", async () => {
const middleware = trailingSlashes("never");
const server = serveMiddleware(async (ctx) => {
ctx.next = async () => new Response("ok");
return await middleware(ctx);
const server = serveMiddleware(middleware, {
next: async () => new Response("ok"),
});
let res = await server.get("/");
+6 -6
View File
@@ -9,14 +9,14 @@ export {
type RouteData,
type RouteHandler,
} from "./handlers.ts";
export { type RouteConfig } from "./types.ts";
export { type Middleware, type MiddlewareFn } from "./middlewares/mod.ts";
export type { RouteConfig } from "./types.ts";
export type { Middleware, MiddlewareFn } from "./middlewares/mod.ts";
export { staticFiles } from "./middlewares/static_files.ts";
export { type Mode, type PageProps } from "./runtime/server/mod.tsx";
export { type FreshConfig, type ResolvedFreshConfig } from "./config.ts";
export { type FreshContext, type Island } from "./context.ts";
export type { Mode } from "./runtime/server/mod.ts";
export type { FreshConfig, ResolvedFreshConfig } from "./config.ts";
export type { FreshContext, Island, PageProps } from "./context.ts";
export { createDefine, type Define } from "./define.ts";
export { type Method } from "./router.ts";
export type { Method } from "./router.ts";
export { HttpError } from "./error.ts";
// Compat with older Fresh versions
+4 -9
View File
@@ -4,7 +4,6 @@ import type { WalkEntry } from "@std/fs/walk";
import * as path from "@std/path";
import type { RouteConfig } from "../../types.ts";
import type { RouteHandler } from "../../handlers.ts";
import type { FreshContext } from "../../context.ts";
import type { MiddlewareFn } from "../../middlewares/mod.ts";
import {
type AsyncAnyComponent,
@@ -13,9 +12,9 @@ import {
import { type Method, pathToPattern } from "../../router.ts";
import { type HandlerFn, isHandlerByMethod } from "../../handlers.ts";
import { type FsAdapter, fsAdapter } from "../../fs.ts";
import type { PageProps } from "../../runtime/server/mod.tsx";
import { HttpError } from "../../error.ts";
import { parseRootPath } from "../../config.ts";
import type { FreshReqContext, PageProps } from "../../context.ts";
const TEST_FILE_PATTERN = /[._]test\.(?:[tj]sx?|[mc][tj]s)$/;
const GROUP_REG = /(^|[/\\\\])\((_[^/\\\\]+)\)[/\\\\]/;
@@ -34,12 +33,8 @@ export interface FreshFsItem<State> {
handler?: RouteHandler<unknown, State> | HandlerFn<unknown, State>[];
handlers?: RouteHandler<unknown, State>;
default?:
| AnyComponent<
PageProps<unknown, State> & Pick<FreshContext<unknown, State>, "redirect">
>
| AsyncAnyComponent<
PageProps<unknown, State> & Pick<FreshContext<unknown, State>, "redirect">
>;
| AnyComponent<PageProps<unknown, State>>
| AsyncAnyComponent<PageProps<unknown, State>>;
}
// deno-lint-ignore no-explicit-any
@@ -324,7 +319,7 @@ function errorMiddleware<State>(
try {
return await ctx.next();
} catch (err) {
ctx.error = err;
(ctx as FreshReqContext<State>).error = err;
return mid(ctx);
}
};
+9 -15
View File
@@ -1,7 +1,7 @@
import { type AnyComponent, h, type RenderableProps, type VNode } from "preact";
import type { MiddlewareFn } from "../../middlewares/mod.ts";
import type { HandlerFn, PageResponse } from "../../handlers.ts";
import type { PageProps } from "../../runtime/server/mod.tsx";
import type { FreshReqContext, PageProps } from "../../context.ts";
export type AsyncAnyComponent<P> = {
(
@@ -30,18 +30,21 @@ export function renderMiddleware<State>(
return res;
}
// deno-lint-ignore no-explicit-any
result = res as any;
result = res;
}
if (components.length === 0) {
throw new Error(`Did not receive any components to render.`);
}
const props = ctx as FreshReqContext<State>;
props.data = result?.data;
let vnode: VNode | null = null;
for (let i = components.length - 1; i >= 0; i--) {
const child = vnode;
const Component = () => child;
// FIXME: remove when we're using `<Slot />`
props.Component = () => child;
const fn = components[i];
@@ -49,23 +52,14 @@ export function renderMiddleware<State>(
typeof fn === "function" &&
fn.constructor.name === "AsyncFunction"
) {
const result = (await fn({ ...ctx, Component })) as VNode | Response;
const result = (await fn(props)) as VNode | Response;
if (result instanceof Response) {
return result;
}
vnode = result;
} else {
// deno-lint-ignore no-explicit-any
vnode = h(components[i] as any, {
config: ctx.config,
url: ctx.url,
req: ctx.req,
params: ctx.params,
state: ctx.state,
Component,
error: ctx.error,
data: result?.data ?? {},
}) as VNode;
vnode = h(components[i] as any, props) as VNode;
}
}
+9
View File
@@ -0,0 +1,9 @@
/**
* The mode Fresh can run in.
*/
export type Mode = "development" | "build" | "production";
export let MODE: Mode = "production";
export function setMode(mode: Mode) {
MODE = mode;
}
-16
View File
@@ -1,16 +0,0 @@
import type { FunctionComponent } from "preact";
import type { FreshContext } from "../../context.ts";
/**
* The mode Fresh can run in.
*/
export type Mode = "development" | "build" | "production";
export let MODE: Mode = "production";
export function setMode(mode: Mode) {
MODE = mode;
}
export type PageProps<Data = unknown, T = unknown> =
& Omit<FreshContext<Data, T>, "next" | "redirect" | "next">
& { Component: FunctionComponent };
+10 -10
View File
@@ -11,7 +11,7 @@ import {
} from "preact";
import type { Signal } from "@preact/signals";
import type { Stringifiers } from "../../jsonify/stringify.ts";
import type { FreshContext } from "../../context.ts";
import type { PageProps } from "../../context.ts";
import { asset, Partial, type PartialProps } from "../shared.ts";
import { stringify } from "../../jsonify/stringify.ts";
import type { ServerIslandRegistry } from "../../context.ts";
@@ -88,7 +88,7 @@ export class RenderState {
hasRuntimeScript = false;
constructor(
public ctx: FreshContext<unknown, unknown>,
public ctx: PageProps<unknown, unknown>,
public islandRegistry: ServerIslandRegistry,
public buildCache: BuildCache,
public partialId: string,
@@ -396,14 +396,14 @@ export function FreshScripts() {
<>
{slots.map((slot) => {
if (slot === null) return null;
// FIXME: Wait for https://github.com/preactjs/preact/pull/4334 to be
// released
return h(
"template",
{ key: slot.id, id: `frsh-${slot.id}-${slot.name}` },
slot.vnode,
// deno-lint-ignore no-explicit-any
) as VNode<any>;
return (
<template
key={slot.id}
id={`frsh-${slot.id}-${slot.name}`}
>
{slot.vnode}
</template>
);
})}
<FreshRuntimeScript />
</>
+10 -5
View File
@@ -1,5 +1,4 @@
import { FreshReqContext } from "./context.ts";
import type { MiddlewareFn } from "./middlewares/mod.ts";
import type { FsAdapter } from "./fs.ts";
import { type BuildCache, ProdBuildCache } from "./build_cache.ts";
import type { ResolvedFreshConfig } from "./config.ts";
@@ -63,22 +62,28 @@ const DEFAULT_CONFIG: ResolvedFreshConfig = {
};
export function serveMiddleware<T>(
middleware: MiddlewareFn<T>,
options: { config?: ResolvedFreshConfig; buildCache?: BuildCache } = {},
middleware: (ctx: FreshReqContext<T>) => Response | Promise<Response>,
options: {
config?: ResolvedFreshConfig;
buildCache?: BuildCache;
next?: () => Promise<Response>;
} = {},
): FakeServer {
return new FakeServer(async (req) => {
const next = () => new Response("not found", { status: 404 });
const next = options.next ??
(() => new Response("not found", { status: 404 }));
const config = options.config ?? DEFAULT_CONFIG;
const buildCache = options.buildCache ??
new ProdBuildCache(config, new Map(), new Map(), true);
const ctx = new FreshReqContext<T>(
req,
DEFAULT_CONN_INFO,
{},
config,
() => Promise.resolve(next()),
new Map(),
buildCache,
DEFAULT_CONN_INFO,
);
return await middleware(ctx);
});