From 675036b33ce98702b880e1532b476bfaaa0587b2 Mon Sep 17 00:00:00 2001 From: Octo8080X <64694349+Octo8080X@users.noreply.github.com> Date: Tue, 30 May 2023 09:29:26 +0900 Subject: [PATCH] feat: add `createHandler()` (#622) I cut out the function that gets an hundler from fresh. The purpose is to prepare you to create tests for your application. The introduction of this feature does not affect fresh. Example: ```typescript main_test.ts /// /// /// /// /// import { createHandler } from "$fresh/server.ts"; import manifest from "./fresh.gen.ts"; import { superdeno } from "https://deno.land/x/superdeno/mod.ts"; import { assertEquals } from "https://deno.land/std@0.148.0/testing/asserts.ts"; import { type RequestHandlerLike, } from "https://deno.land/x/superdeno/src/types.ts"; import { Document, DOMParser, } from "https://deno.land/x/deno_dom/deno-dom-wasm.ts"; Deno.test("HTTP assert test.", async (t) => { await t.step("#1 GET /", async () => { const handler = await createHandler(manifest) as RequestHandlerLike; await superdeno(handler) .get("/") .expect(200); }); await t.step("#2 GET /Foo", async () => { const server = await createHandler(manifest) as RequestHandlerLike; const r = await superdeno(server) .get("/Foo") .expect(200); const document: Document = new DOMParser().parseFromString( r.text, "text/html", )!; assertEquals(document.querySelector("div")?.innerText, "Hello Foo"); }); await t.step("#3 GET /Foo/Bar", async () => { const server = await createHandler(manifest) as RequestHandlerLike; await superdeno(server) .get("/Foo/Bar") .expect(404); }); }); ``` ```sh $ deno test -A main_test.ts Check file:///usr/src/app/my-project/main_test.ts running 1 test from ./main_test.ts HTTP assert test. ... #1 GET / ... ok (53ms) #2 GET /Foo ... ok (50ms) #3 GET /Foo/Bar ... ok (45ms) HTTP assert test. ... ok (154ms) ok | 1 passed (3 steps) | 0 failed (300ms) ``` This was discussed in a separate pull request, but prepared in a separate branch based on @lucacasonato suggestion. [Add a function to get a server class instance.](https://github.com/denoland/fresh/pull/552) Thenk you. --- src/server/mod.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/server/mod.ts b/src/server/mod.ts index 37cec50e..bb4ba980 100644 --- a/src/server/mod.ts +++ b/src/server/mod.ts @@ -60,6 +60,13 @@ export interface DenoConfig { export { ServerContext }; +export async function createHandler( + routes: Manifest, + opts: StartOptions = {}, +) { + const ctx = await ServerContext.fromManifest(routes, opts); + return ctx.handler(); +} export async function start(routes: Manifest, opts: StartOptions = {}) { const ctx = await ServerContext.fromManifest(routes, opts); opts.port ??= 8000;