From b73151851e9fc5e9ca4d9d532749bba6cfcf1fd7 Mon Sep 17 00:00:00 2001 From: Hisam Fahri Date: Thu, 30 Jan 2025 16:08:55 +0700 Subject: [PATCH] :wrench: fix: undefined `route` context on `aot=false` It looks like the `route` context is returning `undefined` if the `aot=false`. This commit try to fix it by passing the `route` to `createDynamicHandler` Fix: [#898](https://github.com/elysiajs/elysia/issues/898) --- src/dynamic-handle.ts | 1 + src/index.ts | 4 ++- test/core/context.test.ts | 56 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 test/core/context.test.ts diff --git a/src/dynamic-handle.ts b/src/dynamic-handle.ts index 2ebc59dc..c071aaad 100644 --- a/src/dynamic-handle.ts +++ b/src/dynamic-handle.ts @@ -62,6 +62,7 @@ export const createDynamicHandler = (app: AnyElysia) => { set, // @ts-expect-error store: app.singleton.store, + route: app._route, request, path, qi, diff --git a/src/index.ts b/src/index.ts index 65f5721a..77135620 100644 --- a/src/index.ts +++ b/src/index.ts @@ -195,6 +195,7 @@ export default class Elysia< private dependencies: Record = {} _routes: Routes = {} as any + _route: string = "" _types = { Prefix: '' as BasePath, @@ -680,7 +681,7 @@ export default class Elysia< validator, hooks, content: localHook?.type as string, - handle + handle, }) if (this.config.strictPath === false) @@ -699,6 +700,7 @@ export default class Elysia< hooks: hooks, compile: handle }) + this._route = path return } diff --git a/test/core/context.test.ts b/test/core/context.test.ts new file mode 100644 index 00000000..cfe42cb0 --- /dev/null +++ b/test/core/context.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from 'bun:test' +import { Elysia } from '../../src' +import { req } from '../utils' + +describe('context', () => { + describe('return route', () => { + it('on aot=true', async () => { + const app = new Elysia().get('/hi/:id', ({ route }) => route) + const res = await app.handle(req('/hi/123')).then((x) => x.text()) + expect(res).toBe('/hi/:id') + }) + + it('on aot=false', async () => { + const app = new Elysia({ aot: false }).get( + '/hi/:id', + ({ route }) => route + ) + const res = await app.handle(req('/hi/123')).then((x) => x.text()) + expect(res).toBe('/hi/:id') + }) + }) + + describe('early return on macros with route data', () => { + it('on aot=true', async () => { + const app = new Elysia() + .macro({ + test: { + beforeHandle({ route }) { + return route + } + } + }) + .get('/hi/:id', () => 'should not returned', { + test: true + }) + const res = await app.handle(req('/hi/123')).then((x) => x.text()) + expect(res).toBe('/hi/:id') + }) + + it('on aot=false', async () => { + const app = new Elysia({ aot: false }) + .macro({ + test: { + beforeHandle({ route }) { + return route + } + } + }) + .get('/hi/:id', () => 'should not returned', { + test: true + }) + const res = await app.handle(req('/hi/123')).then((x) => x.text()) + expect(res).toBe('/hi/:id') + }) + }) +})