feat: add flag to FreshContext for partial requests (#2993)
Addresses a gap between [Fresh v1](https://github.com/denoland/fresh/blob/1.x/src/server/types.ts#L192) and Fresh v2, by adding `ctx.isPartial` to `FreshContext`. The same route (e.g. `GET /api/autocomplete`) can be called from both an Island or a Partial. Returning JSON or HTML depending on the destination of the code. Or is the intent that endpoints returning partials and data should be separated, and this pattern is not to be encouraged in Fresh v2? My use case in Fresh v1 was an `/routes/api/cart.tsx`, which can either just toggle a product from the cart (via cookie), but also update UI elements (e.g. cart icon) based on if called from partial or not. 
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
export const INTERNAL_PREFIX = "/_frsh";
|
||||
export const DEV_ERROR_OVERLAY_URL = `${INTERNAL_PREFIX}/error_overlay`;
|
||||
export const ALIVE_URL = `${INTERNAL_PREFIX}/alive`;
|
||||
export const PARTIAL_SEARCH_PARAM = "fresh-partial";
|
||||
|
||||
+18
-8
@@ -14,7 +14,7 @@ import {
|
||||
RenderState,
|
||||
setRenderState,
|
||||
} from "./runtime/server/preact_hooks.tsx";
|
||||
import { DEV_ERROR_OVERLAY_URL } from "./constants.ts";
|
||||
import { DEV_ERROR_OVERLAY_URL, PARTIAL_SEARCH_PARAM } from "./constants.ts";
|
||||
import { BUILD_ID } from "./runtime/build_id.ts";
|
||||
import { tracer } from "./otel.ts";
|
||||
|
||||
@@ -45,6 +45,14 @@ export interface FreshContext<State = unknown> {
|
||||
readonly params: Record<string, string>;
|
||||
readonly error: unknown;
|
||||
readonly info: Deno.ServeHandlerInfo;
|
||||
/**
|
||||
* Whether the current Request is a partial request.
|
||||
*
|
||||
* Partials in Fresh will append the query parameter
|
||||
* {@linkcode PARTIAL_SEARCH_PARAM} to the URL. This property can
|
||||
* be used to determine if only `<Partial>`'s need to be rendered.
|
||||
*/
|
||||
readonly isPartial: boolean;
|
||||
/**
|
||||
* Return a redirect response to the specified path. This is the
|
||||
* preferred way to do redirects in Fresh.
|
||||
@@ -90,14 +98,15 @@ export let getBuildCache: (ctx: FreshContext<unknown>) => BuildCache;
|
||||
|
||||
export class FreshReqContext<State>
|
||||
implements FreshContext<State>, PageProps<unknown, State> {
|
||||
config: ResolvedFreshConfig;
|
||||
url: URL;
|
||||
req: Request;
|
||||
params: Record<string, string>;
|
||||
state: State = {} as State;
|
||||
readonly config: ResolvedFreshConfig;
|
||||
readonly url: URL;
|
||||
readonly req: Request;
|
||||
readonly params: Record<string, string>;
|
||||
readonly state: State = {} as State;
|
||||
data: unknown = undefined;
|
||||
error: unknown | null = null;
|
||||
info: Deno.ServeHandlerInfo | Deno.ServeHandlerInfo;
|
||||
readonly info: Deno.ServeHandlerInfo | Deno.ServeHandlerInfo;
|
||||
readonly isPartial: boolean;
|
||||
|
||||
next: FreshContext<State>["next"];
|
||||
|
||||
@@ -126,6 +135,7 @@ export class FreshReqContext<State>
|
||||
this.info = info;
|
||||
this.params = params;
|
||||
this.config = config;
|
||||
this.isPartial = url.searchParams.has(PARTIAL_SEARCH_PARAM);
|
||||
this.next = next;
|
||||
this.#islandRegistry = islandRegistry;
|
||||
this.#buildCache = buildCache;
|
||||
@@ -181,7 +191,7 @@ export class FreshReqContext<State>
|
||||
};
|
||||
|
||||
let partialId = "";
|
||||
if (this.url.searchParams.has("fresh-partial")) {
|
||||
if (this.url.searchParams.has(PARTIAL_SEARCH_PARAM)) {
|
||||
partialId = crypto.randomUUID();
|
||||
headers.set("X-Fresh-Id", partialId);
|
||||
}
|
||||
|
||||
@@ -69,3 +69,18 @@ Deno.test("ctx.render - throw with invalid first arg", async () => {
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(500);
|
||||
});
|
||||
|
||||
Deno.test("ctx.isPartial - should indicate whether request is partial or not", async () => {
|
||||
const isPartials: boolean[] = [];
|
||||
const app = new App()
|
||||
.get("/", (ctx) => {
|
||||
isPartials.push(ctx.isPartial);
|
||||
return new Response("ok");
|
||||
});
|
||||
const server = new FakeServer(app.handler());
|
||||
|
||||
await server.get("/");
|
||||
await server.get("/?fresh-partial");
|
||||
|
||||
expect(isPartials).toEqual([false, true]);
|
||||
});
|
||||
|
||||
@@ -21,10 +21,9 @@ import {
|
||||
import { createRootFragment, isCommentNode, isElementNode } from "./reviver.ts";
|
||||
import type { PartialStateJson } from "../server/preact_hooks.tsx";
|
||||
import { parse } from "../../jsonify/parse.ts";
|
||||
import { INTERNAL_PREFIX } from "../../constants.ts";
|
||||
import { INTERNAL_PREFIX, PARTIAL_SEARCH_PARAM } from "../../constants.ts";
|
||||
|
||||
export const PARTIAL_ATTR = "f-partial";
|
||||
export const PARTIAL_SEARCH_PARAM = "fresh-partial";
|
||||
|
||||
class NoPartialsError extends Error {}
|
||||
|
||||
|
||||
@@ -25,7 +25,10 @@ import {
|
||||
} from "../shared_internal.tsx";
|
||||
import type { BuildCache } from "../../build_cache.ts";
|
||||
import { BUILD_ID } from "../build_id.ts";
|
||||
import { DEV_ERROR_OVERLAY_URL } from "../../constants.ts";
|
||||
import {
|
||||
DEV_ERROR_OVERLAY_URL,
|
||||
PARTIAL_SEARCH_PARAM,
|
||||
} from "../../constants.ts";
|
||||
import * as colors from "@std/fmt/colors";
|
||||
import { escape as escapeHtml } from "@std/html";
|
||||
import { HttpError } from "../../error.ts";
|
||||
@@ -427,7 +430,7 @@ function FreshRuntimeScript() {
|
||||
|
||||
const islandArr = Array.from(islands);
|
||||
|
||||
if (ctx.url.searchParams.has("fresh-partial")) {
|
||||
if (ctx.url.searchParams.has(PARTIAL_SEARCH_PARAM)) {
|
||||
const islands = islandArr.map((island) => {
|
||||
const chunk = buildCache.getIslandChunkName(island.name);
|
||||
if (chunk === null) {
|
||||
|
||||
Reference in New Issue
Block a user