From a0e8f15c7bd8e5e7d953541bb2cd65f8eb8536ac Mon Sep 17 00:00:00 2001 From: Tom Gobich Date: Wed, 22 Nov 2023 05:43:56 -0500 Subject: [PATCH] fix: clearing slash prefixes before adding uriSegment within url builder's processPattern (#77) --- src/router/lookup_store/url_builder.ts | 3 ++- tests/router/url_builder.spec.ts | 33 ++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/router/lookup_store/url_builder.ts b/src/router/lookup_store/url_builder.ts index 58624ae..656876a 100644 --- a/src/router/lookup_store/url_builder.ts +++ b/src/router/lookup_store/url_builder.ts @@ -110,7 +110,8 @@ export class UrlBuilder { * we must break out from the loop */ if (token.type === 0) { - uriSegments.push(`${token.val}${token.end}`) + const value = token.val.startsWith('/') ? token.val.substring(1) : token.val + uriSegments.push(`${value}${token.end}`) } else if (token.type === 2) { const values: string[] = paramsArray ? paramsArray.slice(paramsIndex) : paramsObject['*'] this.#ensureHasWildCardValues(pattern, values) diff --git a/tests/router/url_builder.spec.ts b/tests/router/url_builder.spec.ts index 879e5a8..8b67aa6 100644 --- a/tests/router/url_builder.spec.ts +++ b/tests/router/url_builder.spec.ts @@ -52,6 +52,23 @@ test.group('URL builder', () => { assert.equal(lookupStore.builder().params([1]).make('users.show'), '/users/1') }) + test('create url for a route by its name for the home path', ({ assert }) => { + const app = new AppFactory().create(BASE_URL, () => {}) + const encryption = new EncryptionFactory().create() + const lookupStore = new LookupStore(encryption, new QsParserFactory().create()) + + const route = new Route(app, [], { + pattern: '/', + globalMatchers: {}, + handler: () => {}, + methods: ['GET'], + }) + route.as('home') + + lookupStore.register(route.toJSON()) + assert.equal(lookupStore.builder().make('home'), '/') + }) + test('create url for a route by the handler name', ({ assert }) => { const app = new AppFactory().create(BASE_URL, () => {}) const encryption = new EncryptionFactory().create() @@ -68,6 +85,22 @@ test.group('URL builder', () => { assert.equal(lookupStore.builder().params([1]).make('#controllers/posts'), '/users/1') }) + test('create url for a route by the handler name for the home path', ({ assert }) => { + const app = new AppFactory().create(BASE_URL, () => {}) + const encryption = new EncryptionFactory().create() + const lookupStore = new LookupStore(encryption, new QsParserFactory().create()) + + const route = new Route(app, [], { + pattern: '/', + globalMatchers: {}, + handler: '#controllers/home', + methods: ['GET'], + }) + + lookupStore.register(route.toJSON()) + assert.equal(lookupStore.builder().params([1]).make('#controllers/home'), '/') + }) + test('raise error when unable to lookup route', ({ assert }) => { const encryption = new EncryptionFactory().create() const lookupStore = new LookupStore(encryption, new QsParserFactory().create())