Skip to content

Commit

Permalink
Avoid rebuilding UrlPattern instances
Browse files Browse the repository at this point in the history
  • Loading branch information
megamaddu authored and pedronauck committed May 19, 2017
1 parent 72d89fa commit 4b449fb
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
5 changes: 4 additions & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const UrlPattern = require('url-pattern')
const { getParamsAndQuery } = require('../utils')

const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']
Expand All @@ -6,8 +7,10 @@ const methodFn = method => (path, handler) => {
if (!path) throw new Error('You need to set a valid path')
if (!handler) throw new Error('You need to set a valid handler')

const route = new UrlPattern(path)

return (req, res) => {
const { params, query } = getParamsAndQuery(path, req.url)
const { params, query } = getParamsAndQuery(route, req.url)

if (params && req.method === method) {
return handler(Object.assign(req, { params, query }), res)
Expand Down
8 changes: 5 additions & 3 deletions utils/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
const { parse } = require('url')
const UrlPattern = require('url-pattern')

const getParamsAndQuery = (pattern, url) => {
const getParamsAndQuery = (patternOrRoute, url) => {
const { query, pathname } = parse(url, true)
const route = new UrlPattern(pattern)
const params = route.match(pathname)

const route =
patternOrRoute instanceof UrlPattern ? patternOrRoute : new UrlPattern(patternOrRoute)

const params = route.match(pathname)
return { query, params }
}

Expand Down
11 changes: 11 additions & 0 deletions utils/index.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const test = require('ava')
const UrlPattern = require('url-pattern')

const { getParamsAndQuery } = require('./')

Expand All @@ -11,3 +12,13 @@ test('getParamsAndQuery()', t => {
t.deepEqual(params, { msg: 'world' })
t.deepEqual(query, { id: '0' })
})

test('getParamsAndQuery() with UrlPattern', t => {
const route = new UrlPattern('/hello/:msg')
const url = '/hello/world?id=0'

const { params, query } = getParamsAndQuery(route, url)

t.deepEqual(params, { msg: 'world' })
t.deepEqual(query, { id: '0' })
})

0 comments on commit 4b449fb

Please sign in to comment.