Skip to content

Commit

Permalink
Use servie-url for better cache re-use
Browse files Browse the repository at this point in the history
  • Loading branch information
blakeembrey committed May 19, 2019
1 parent bd10e1a commit 5bd75e8
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 33 deletions.
5 changes: 5 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@
},
"dependencies": {
"debug": "^4.1.1",
"path-to-regexp": "^3.0.0"
"path-to-regexp": "^3.0.0",
"servie-url": "^1.0.0"
}
}
34 changes: 2 additions & 32 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import debug = require("debug");
import pathToRegexp = require("path-to-regexp");
import { Request, Response } from "servie";
import { parse } from "url";
import { getURL } from "servie-url";

const log = debug("servie-route");

Expand All @@ -28,7 +28,7 @@ export function create(verb?: string) {
return function(req: T, next: () => Promise<U>): Promise<U> {
if (!matches(req.method)) return next();

const pathname = getPathname(req);
const { pathname } = getURL(req);
const m = re.exec(pathname);

if (!m) return next();
Expand Down Expand Up @@ -74,33 +74,3 @@ function toMatch(verb?: string): (method: string) => boolean {

return m => m.toLowerCase() === method;
}

type PathCache = { pathname: string; url: string };
const map = new WeakMap<Request, PathCache>();

/**
* Parse pathname from request url.
*/
function parsePathname(req: Request) {
return parse(req.url).pathname || "/";
}

/**
* Parse pathname from request instance.
*/
function getPathname(req: Request): string {
const { url } = req;

if (!map.has(req)) {
const pathname = parsePathname(req);
map.set(req, { pathname, url });
return pathname;
}

const cache = map.get(req)!;
if (cache.url === req.url) return cache.pathname;

const pathname = parsePathname(req);
map.set(req, { pathname, url });
return pathname;
}

0 comments on commit 5bd75e8

Please sign in to comment.