Преглед изворни кода

notfound use patterns values not keys

Shaun пре 2 година
родитељ
комит
4b6d831906
3 измењених фајлова са 13 додато и 6 уклоњено
  1. 1 1
      package.json
  2. 9 5
      src/router.js
  3. 3 0
      tests/router.test.js

+ 1 - 1
package.json

@@ -1,6 +1,6 @@
 {
   "name": "@shaun/alpinejs-router",
-  "version": "1.2.6",
+  "version": "1.2.7",
   "description": "Easy to use and flexible router for Alpine.js",
   "type": "module",
   "main": "dist/module.cjs.js",

+ 9 - 5
src/router.js

@@ -14,8 +14,9 @@ export class Router {
 
   match (target) {
     console.assert(target instanceof RouterURL)
+    const path = target.path
     for (const [route, pattern] of Object.entries(this.#patterns)) {
-      const found = URLPattern.match(target.path, pattern)
+      const found = URLPattern.match(path, pattern)
       if (found) {
         return found === true ? {} : found
       }
@@ -25,10 +26,11 @@ export class Router {
 
   is (target, ...routes) {
     console.assert(target instanceof RouterURL)
+    const path = target.path
     for (const route of routes) {
       const pattern = this.#patterns[route] ?? this.#cache[route] ?? URLPattern.build(route)
       this.#cache[route] = pattern
-      if (URLPattern.is(target.path, pattern)) {
+      if (URLPattern.is(path, pattern)) {
         return true
       }
     }
@@ -37,10 +39,11 @@ export class Router {
 
   not (target, ...routes) {
     console.assert(target instanceof RouterURL)
+    const path = target.path
     for (const route of routes) {
       const pattern = this.#patterns[route] ?? this.#cache[route] ?? URLPattern.build(route)
       this.#cache[route] = pattern
-      if (URLPattern.is(target.path, pattern)) {
+      if (URLPattern.is(path, pattern)) {
         return false
       }
     }
@@ -49,8 +52,9 @@ export class Router {
 
   notfound (target) {
     console.assert(target instanceof RouterURL)
-    return Object.keys(this.#patterns).findIndex(
-      e => URLPattern.is(target.path, e)
+    const path = target.path
+    return Object.values(this.#patterns).findIndex(
+      e => URLPattern.is(path, e)
     ) === -1
   }
 }

+ 3 - 0
tests/router.test.js

@@ -18,6 +18,7 @@ describe('router', () => {
     r.add('/hello')
     r.add('/users/add')
     r.add('/users/:id')
+    r.add('/users/:id/edit')
     let url = new RouterURL('http:/localhost/hello')
     expect(r.is(url, '/hello')).toBe(true)
     expect(r.is(url, '/xyz')).toBe(false)
@@ -33,5 +34,7 @@ describe('router', () => {
     expect(r.is(url, '/users/:id(\\d+)')).toBe(true)
     expect(r.notfound(new RouterURL('http:/localhost/hello/world'))).toBe(true)
     expect(r.notfound(new RouterURL('http:/localhost/hello'))).toBe(false)
+    url = new RouterURL('http:/localhost/users/123/edit')
+    expect(r.is(url, '/users/:id(\\d+)/edit')).toBe(true)
   })
 })