Add match-route

pull/282/head
amio 2019-05-15 21:13:07 +08:00
rodzic da42d52825
commit f2b784d41e
3 zmienionych plików z 78 dodań i 2 usunięć

Wyświetl plik

@ -1,8 +1,8 @@
import url from 'url'
import PathParser from 'path-parser'
import serve404 from './serve-404'
import serveBadge from './serve-badge'
import matchRoute from './match-route'
import { BadgenParams } from './types'
@ -22,7 +22,7 @@ export function badgenServe (handlers: BadgenServeHandlers): Function {
// Lookup handler
let matchedArgs
const matchedScheme = Object.keys(handlers).find(scheme => {
matchedArgs = new PathParser(scheme).test(pathname)
matchedArgs = matchRoute(scheme, decodeURI(pathname))
return matchedArgs !== null
})

Wyświetl plik

@ -0,0 +1,52 @@
type RouteArgs = null | {
[key: string]: string
}
function matchRoute(pattern: string, path: string): RouteArgs {
const parsedArgs: RouteArgs = {}
const PATTERN_SEGMENT_REG = /\/(:)?([\w-]+)([*?+]){0,1}(?:<(.+)>)?/g
const PATH_SEGMENT_REG = /\/([^/]+)/g
let parsedPatternSegment = PATTERN_SEGMENT_REG.exec(pattern)
let parsedPathSegment = PATH_SEGMENT_REG.exec(path)
while (parsedPatternSegment !== null) {
const [ rawPatternSegment, type, name, flag, reg ] = parsedPatternSegment
if (parsedPathSegment === null) {
return flag === '?' ? parsedArgs : null
}
const [ rawPathSegment, value ] = parsedPathSegment
switch (type) {
case undefined: // literal match
if (rawPatternSegment !== rawPathSegment) {
return null
}
break
case ':': // named segment
if (reg) {
if (new RegExp(`^${reg}$`).test(value)) {
parsedArgs[name] = value
} else {
return null
}
} else {
parsedArgs[name] = value
}
}
parsedPatternSegment = PATTERN_SEGMENT_REG.exec(pattern)
parsedPathSegment = PATH_SEGMENT_REG.exec(path)
}
if (parsedPathSegment === null) {
return parsedArgs
} else {
return null
}
}
export default matchRoute

Wyświetl plik

@ -0,0 +1,24 @@
import matchRoute from '../libs/match-route'
const matcher = route => path => {
const result = matchRoute(route, path)
console.log('\n', route, '\n', path, '\n', result)
return result
}
const route = '/github/:topic<stars|forks>/:owner/:repo/:chanel?/:more?'
const parsed = [
'/github/stars/amio/',
'/github/eiyou/amio/badgen',
'/github/stars/amio/badgen',
'/github/stars/amio/badgen',
'/github/stars/amio/badgen/master',
'/github/stars/amio/badgen/master/',
'/github/stars/amio/badgen/master/more',
].map(matcher(route))
const route2 = '/user/:id<\\d+>'
const parsed2 = [
'/user/123',
'/user/sd'
].map(matcher(route2))