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
Provenance
- Commit
a2d2280- Tree
50396d4- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
390d05b
4 files changed+225 added−4 removed
modified:deno_dist/context.ts-3 removed
63 unmodified lines64 executionCtx?: FetchEvent | ExecutionContext | undefined65 notFoundHandler?: NotFoundHandler<E>66 path?: string67 paramData?: Record<string, string>68- routerName?: string68 }69 70 export class Context<71 // eslint-disable-next-line @typescript-eslint/no-explicit-any4 unmodified lines76 > {77 env: E['Bindings'] = {}78 finalized: boolean = false79 error: Error | undefined = undefined81- routerName?: string | undefined80 81 // eslint-disable-next-line @typescript-eslint/no-explicit-any82 private _req?: HonoRequest<any, any>83 private _status: StatusCode = 20014 unmodified lines98 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 linesmodified:deno_dist/hono-base.ts+37 added-1 removed
192 unmodified lines193 )194 })195 }196 197+ /**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+ )220+221+ if (res) return res222+223+ await next()224+ }225+ this.addRoute(METHOD_NAME_ALL, mergePath(path, '*'), handler)226+ return this227+ }228+229+ get routerName() {230+ this.matchRoute('GET', '/')231+ return this.router.name232+ }233+234 private addRoute(method: string, path: string, handler: H) {235 method = method.toUpperCase()236 if (this._basePath) {237 path = mergePath(this._basePath, path)30 unmodified lines268 executionCtx: eventOrExecutionCtx,269 notFoundHandler: this.notFoundHandler,270 path,271 paramData,235- routerName: this.router.name,272 })273 274 // Do not `compose` if it has only one handler275 if (result?.handlers.length === 1) {87 unmodified linesmodified:src/hono-base.ts+32 added
192 unmodified lines193 )194 })195 }196 197+ /**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+ )220+221+ if (res) return res222+223+ await next()224+ }225+ this.addRoute(METHOD_NAME_ALL, mergePath(path, '*'), handler)226+ return this227+ }228+229 get routerName() {230 this.matchRoute('GET', '/')231 return this.router.name232 }130 unmodified linesmodified:src/hono.test.ts+156 added
8 unmodified lines9 import { RegExpRouter } from './router/reg-exp-router'10 import { TrieRouter } from './router/trie-router'11 import type { Handler, Next } from './types'12 import type { Expect, Equal } from './utils/types'13+import { getPath } from './utils/url'14 15 // https://stackoverflow.com/a/6566640216 function throwExpression(errorMessage: string): never {17 throw new Error(errorMessage)1893 unmodified lines1911 })1912 })1913 })1914 1915+describe('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+ }1947+1948+ 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)1958+1959+ const api = new Hono().basePath('/api')1960+ api.mount('/another-app', anotherApp)1961+1962+ 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+ })1968+1969+ 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')1974+1975+ 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')1979+1980+ 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!')1989+1990+ 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')1994+1995+ 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+ })2001+2002+ 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+ })2007+2008+ 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+ })2014+2015+ 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+ }2035+2036+ const app = new Hono()2037+ app.mount('/another-app', anotherApp)2038+2039+ 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+})2069+2070 describe('Router Name', () => {2071 it('Should return the correct router name', async () => {2072 const app = new Hono({2073 router: new RegExpRouter(),8 unmodified lines