Skip to content
Myr

feat: `app.mount()` (#1104)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* feat: `mount()` * update tests * check header values * chore: denoify * make it as `app.mount()` * denoify * Generate new URL more simply. (#1112) * Generate new URL more simply. * chore: denoify ---------

authored by Yusuke Wada · committed by GitHub · parent 390d05b · Browse files · 4 files+225 added−4 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Taku Amano <taku@taaas.jp>

Diff stats

4 files+225 added−4 removed

  • tests:+156 added−0 removed
  • other:+69 added−4 removed

4 files+225 added−4 removed

modified:deno_dist/context.ts-3 removed
63 unmodified lines
64 executionCtx?: FetchEvent | ExecutionContext | undefined65 notFoundHandler?: NotFoundHandler<E>66 path?: string67 paramData?: Record<string, string>68 routerName?: string68}6970export class Context<71 // eslint-disable-next-line @typescript-eslint/no-explicit-any
4 unmodified lines
76> {77 env: E['Bindings'] = {}78 finalized: boolean = false79 error: Error | undefined = undefined81 routerName?: string | undefined8081 // eslint-disable-next-line @typescript-eslint/no-explicit-any82 private _req?: HonoRequest<any, any>83 private _status: StatusCode = 200
14 unmodified lines
98 if (options) {99 this._exCtx = options.executionCtx100 this._path = options.path ?? '/'101 this._pData = options.paramData104 this.routerName = options.routerName102 this.env = options.env103 if (options.notFoundHandler) {104 this.notFoundHandler = options.notFoundHandler105 }
294 unmodified lines
modified:deno_dist/hono-base.ts+37 added-1 removed
192 unmodified lines
193 )194 })195 }196197 /**198 * @experimental199 * `app.mount()` is an experimental feature.200 * The API might be changed.201 */202 mount(203 path: string,204 // eslint-disable-next-line @typescript-eslint/no-explicit-any205 applicationHandler: (request: Request, ...args: any) => Response | Promise<Response>,206 optionHandler?: (c: Context) => unknown207 ): Hono<E, S, BasePath> {208 const pathPrefixLength = mergePath(this._basePath, path).length209 const handler: MiddlewareHandler = async (c, next) => {210 let executionContext: ExecutionContext | undefined = undefined211 try {212 executionContext = c.executionCtx213 } catch {} // Do nothing214 const options = optionHandler ? optionHandler(c) : [c.env, executionContext]215 const optionsArray = Array.isArray(options) ? options : [options]216 const res = await applicationHandler(217 new Request(new URL(c.req.path.slice(pathPrefixLength) || '/', c.req.url), c.req.raw),218 ...optionsArray219 )220221 if (res) return res222223 await next()224 }225 this.addRoute(METHOD_NAME_ALL, mergePath(path, '*'), handler)226 return this227 }228229 get routerName() {230 this.matchRoute('GET', '/')231 return this.router.name232 }233234 private addRoute(method: string, path: string, handler: H) {235 method = method.toUpperCase()236 if (this._basePath) {237 path = mergePath(this._basePath, path)
30 unmodified lines
268 executionCtx: eventOrExecutionCtx,269 notFoundHandler: this.notFoundHandler,270 path,271 paramData,235 routerName: this.router.name,272 })273274 // Do not `compose` if it has only one handler275 if (result?.handlers.length === 1) {
87 unmodified lines
modified:src/hono-base.ts+32 added
192 unmodified lines
193 )194 })195 }196197 /**198 * @experimental199 * `app.mount()` is an experimental feature.200 * The API might be changed.201 */202 mount(203 path: string,204 // eslint-disable-next-line @typescript-eslint/no-explicit-any205 applicationHandler: (request: Request, ...args: any) => Response | Promise<Response>,206 optionHandler?: (c: Context) => unknown207 ): Hono<E, S, BasePath> {208 const pathPrefixLength = mergePath(this._basePath, path).length209 const handler: MiddlewareHandler = async (c, next) => {210 let executionContext: ExecutionContext | undefined = undefined211 try {212 executionContext = c.executionCtx213 } catch {} // Do nothing214 const options = optionHandler ? optionHandler(c) : [c.env, executionContext]215 const optionsArray = Array.isArray(options) ? options : [options]216 const res = await applicationHandler(217 new Request(new URL(c.req.path.slice(pathPrefixLength) || '/', c.req.url), c.req.raw),218 ...optionsArray219 )220221 if (res) return res222223 await next()224 }225 this.addRoute(METHOD_NAME_ALL, mergePath(path, '*'), handler)226 return this227 }228229 get routerName() {230 this.matchRoute('GET', '/')231 return this.router.name232 }
130 unmodified lines
modified:src/hono.test.ts+156 added
8 unmodified lines
9import { RegExpRouter } from './router/reg-exp-router'10import { TrieRouter } from './router/trie-router'11import type { Handler, Next } from './types'12import type { Expect, Equal } from './utils/types'13import { getPath } from './utils/url'1415// https://stackoverflow.com/a/6566640216function throwExpression(errorMessage: string): never {17 throw new Error(errorMessage)
1893 unmodified lines
1911 })1912 })1913})19141915describe('app.mount()', () => {1916 describe('Basic', () => {1917 const anotherApp = (req: Request, params: unknown) => {1918 const path = getPath(req)1919 console.log(`path in anotherApp: ${path}`)1920 if (path === '/') {1921 return new Response('AnotherApp')1922 }1923 if (path === '/hello') {1924 return new Response('Hello from AnotherApp')1925 }1926 if (path === '/header') {1927 const message = req.headers.get('x-message')1928 return new Response(message)1929 }1930 if (path == '/with-params') {1931 return new Response(1932 JSON.stringify({1933 params,1934 }),1935 {1936 headers: {1937 'Content-Type': 'application.json',1938 },1939 }1940 )1941 }1942 console.log(`before 404 ${req.url}`)1943 return new Response('Not Found from AnotherApp', {1944 status: 404,1945 })1946 }19471948 const app = new Hono()1949 app.use('*', async (c, next) => {1950 await next()1951 c.header('x-message', 'Foo')1952 })1953 app.get('/', (c) => c.text('Hono'))1954 app.mount('/another-app', anotherApp, () => {1955 return 'params'1956 })1957 app.mount('/another-app2/sub-slash/', anotherApp)19581959 const api = new Hono().basePath('/api')1960 api.mount('/another-app', anotherApp)19611962 it('Should return responses from Hono app', async () => {1963 const res = await app.request('/')1964 expect(res.status).toBe(200)1965 expect(res.headers.get('x-message')).toBe('Foo')1966 expect(await res.text()).toBe('Hono')1967 })19681969 it('Should return responses from AnotherApp', async () => {1970 let res = await app.request('/another-app')1971 expect(res.status).toBe(200)1972 expect(res.headers.get('x-message')).toBe('Foo')1973 expect(await res.text()).toBe('AnotherApp')19741975 res = await app.request('/another-app/hello')1976 expect(res.status).toBe(200)1977 expect(res.headers.get('x-message')).toBe('Foo')1978 expect(await res.text()).toBe('Hello from AnotherApp')19791980 const req = new Request('http://localhost/another-app/header', {1981 headers: {1982 'x-message': 'Message Foo!',1983 },1984 })1985 res = await app.request(req)1986 expect(res.status).toBe(200)1987 expect(res.headers.get('x-message')).toBe('Foo')1988 expect(await res.text()).toBe('Message Foo!')19891990 res = await app.request('/another-app/not-found')1991 expect(res.status).toBe(404)1992 expect(res.headers.get('x-message')).toBe('Foo')1993 expect(await res.text()).toBe('Not Found from AnotherApp')19941995 res = await app.request('/another-app/with-params')1996 expect(res.status).toBe(200)1997 expect(await res.json()).toEqual({1998 params: 'params',1999 })2000 })20012002 it('Should return responses from AnotherApp - sub + slash', async () => {2003 const res = await app.request('/another-app2/sub-slash')2004 expect(res.status).toBe(200)2005 expect(await res.text()).toBe('AnotherApp')2006 })20072008 it('Should return responses from AnotherApp - with `basePath()`', async () => {2009 const res = await api.request('/api/another-app')2010 expect(res.status).toBe(200)2011 expect(await res.text()).toBe('AnotherApp')2012 })2013 })20142015 describe('With fetch', () => {2016 const anotherApp = async (req: Request, env: {}, executionContext: ExecutionContext) => {2017 const path = getPath(req)2018 if (path === '/') {2019 return new Response(2020 JSON.stringify({2021 env,2022 executionContext,2023 }),2024 {2025 headers: {2026 'Content-Type': 'application/json',2027 },2028 }2029 )2030 }2031 return new Response('Not Found from AnotherApp', {2032 status: 404,2033 })2034 }20352036 const app = new Hono()2037 app.mount('/another-app', anotherApp)20382039 it('Should handle Env and ExecuteContext', async () => {2040 const request = new Request('http://localhost/another-app')2041 const res = await app.fetch(2042 request,2043 {2044 TOKEN: 'foo',2045 },2046 {2047 // Force mocking!2048 // eslint-disable-next-line @typescript-eslint/ban-ts-comment2049 // @ts-ignore2050 waitUntil: 'waitUntil',2051 // eslint-disable-next-line @typescript-eslint/ban-ts-comment2052 // @ts-ignore2053 passThroughOnException: 'passThroughOnException',2054 }2055 )2056 expect(res.status).toBe(200)2057 expect(await res.json()).toEqual({2058 env: {2059 TOKEN: 'foo',2060 },2061 executionContext: {2062 waitUntil: 'waitUntil',2063 passThroughOnException: 'passThroughOnException',2064 },2065 })2066 })2067 })2068})20692070describe('Router Name', () => {2071 it('Should return the correct router name', async () => {2072 const app = new Hono({2073 router: new RegExpRouter(),
8 unmodified lines