feat: add render function (#2454)

This commit is contained in:
Luca Casonato
2024-05-24 18:31:34 +02:00
committed by GitHub
parent 82d027cbcd
commit f2162d24bf
14 changed files with 123 additions and 64 deletions
+45 -4
View File
@@ -1,10 +1,52 @@
import type { FreshContext } from "./context.ts";
import type { Method } from "./router.ts";
export interface Render<T> {
export interface PageResponse<T> {
data: T;
headers: Headers;
status: number;
}
/**
* Create a {@link PageResponse} object that can be returned from a route
* handler. This will cause the page component to be rendered with the specified
* data and response options.
*
* ```ts
* export const handlers = define.handlers({
* GET: (ctx) => {
* return page({ message: "Hello, world!" }, {
* headers: { "Cache-Control": "public, max-age=3600" },
* status: 201,
* });
* },
* });
*
* export default define.page<typeof handlers>(({ data }) => {
* return <h1>{data.message}</h1>;
* });
* ```
*
* @param data The data to pass to the page component to be rendered.
* @param options Additional options to use when constructing the response object.
* @returns A {@link PageResponse} object that should be returned from a route handler.
*/
export function page<T>(data: T, options?: {
headers?: HeadersInit;
status?: number;
}): PageResponse<T>;
export function page(): PageResponse<undefined>;
export function page<T>(data?: T, options?: {
headers?: HeadersInit;
status?: number;
}): PageResponse<T> {
return {
data: data ?? undefined as T,
headers: options?.headers instanceof Headers
? options.headers
: new Headers(options?.headers),
status: options?.status ?? 200,
};
}
/**
@@ -152,9 +194,8 @@ export function isHandlerByMethod<D, S>(
export interface HandlerFn<Data, State> {
(ctx: FreshContext<Data, State>):
| Response
| Render<Data>
| void
| Promise<Response | Render<Data> | void>;
| PageResponse<Data>
| Promise<Response | PageResponse<Data>>;
}
/**