Skip to content

Commit

Permalink
path to ctx
Browse files Browse the repository at this point in the history
  • Loading branch information
herudi committed May 22, 2022
1 parent 4e40e79 commit 8ceb1dd
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 39 deletions.
42 changes: 29 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
## Van Router

[![ci](https://github.com/herudi/van-router/workflows/ci/badge.svg)](https://github.com/herudi/van-router)
[![npm version](https://img.shields.io/badge/npm-0.6.1-blue.svg)](https://npmjs.org/package/van-router)
[![npm version](https://img.shields.io/badge/npm-0.6.2-blue.svg)](https://npmjs.org/package/van-router)
[![License](https://img.shields.io/:license-mit-blue.svg)](http://badges.mit-license.org)
[![download-url](https://img.shields.io/npm/dm/van-router.svg)](https://npmjs.org/package/van-router)
[![minzip](https://img.shields.io/bundlephobia/minzip/van-router)](https://github.com/herudi/van-router)
Expand Down Expand Up @@ -47,7 +47,7 @@ const { createRouter } = require("van-router");
### Deno

```ts
import { createRouter } from "https://deno.land/x/van_router@0.6.1/mod.ts";
import { createRouter } from "https://deno.land/x/van_router@0.6.2/mod.ts";
```

## Usage
Expand Down Expand Up @@ -464,6 +464,22 @@ router.add("/about", () => {
router.resolve();
```

## Server-Rendered

```js
// resolve in the server.
const res = router.resolve({ request, response });

// body / elem
const body = await res.out();

// initial data from useData.
const data = await res.data();

// head for seo from setHead.
const head = res.head();
```

## With Nodejs (Server-Rendered)

```js
Expand All @@ -480,10 +496,10 @@ router.add("/", ({ html, setHead }) => {
});

http.createServer(async (request, response) => {
const van = router.resolve({ request, response });
const elem = await van.out();
const head = van.head();
if (typeof elem === "string") {
const res = router.resolve({ request, response });
const body = await res.out();
const head = res.head();
if (typeof body === "string") {
response.setHeader("Content-Type", "text/html");
response.end(`
<html>
Expand All @@ -492,7 +508,7 @@ http.createServer(async (request, response) => {
${head}
</head>
<body>
${elem}
${body}
</body>
</html>
`);
Expand All @@ -503,7 +519,7 @@ http.createServer(async (request, response) => {
## With Deno (Server-Rendered)

```ts
import { createRouter } from "https://deno.land/x/van_router@0.6.1/mod.ts";
import { createRouter } from "https://deno.land/x/van_router@0.6.2/mod.ts";
import { serve } from "https://deno.land/std@0.140.0/http/server.ts";

const port = 8080;
Expand All @@ -516,10 +532,10 @@ router.add("/", ({ html, setHead }) => {
});

await serve(async (request: Request) => {
const van = router.resolve({ request });
const elem = await van.out();
const head = van.head();
if (elem instanceof Response) return elem;
const res = router.resolve({ request });
const body = await res.out();
const head = res.head();
if (body instanceof Response) return body;
return new Response(
`
<html>
Expand All @@ -528,7 +544,7 @@ await serve(async (request: Request) => {
${head}
</head>
<body>
${elem}
${body}
</body>
</html>
`,
Expand Down
43 changes: 18 additions & 25 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export interface Context {
route: {
url: string;
pathname: string;
path: string | RegExp;
params: TObject;
go(url: string, type?: string): void;
};
Expand Down Expand Up @@ -47,21 +48,6 @@ type TOptions = {
base?: string;
hash?: boolean;
};

function concatRegexp(prefix: string, path: RegExp) {
if (prefix === "") return path;
const regex = new RegExp(prefix);
return new RegExp(regex.source + path.source);
}

const decURI = (str: string) => {
try {
return decodeURI(str);
} catch (_e) {
return str;
}
};

// deno-lint-ignore ban-ts-comment
// @ts-ignore
export const IS_CLIENT = typeof window !== "undefined" &&
Expand Down Expand Up @@ -109,8 +95,10 @@ class Router<Ctx extends Context = Context> {
const fns = [].slice.call(arguments, 2);
this._route[method] = this._route[method] || [];
if (path instanceof RegExp) {
const regex = concatRegexp(this.base, path);
this._route[method].push({ fns, regex });
const regex = this.base === ""
? path
: new RegExp(new RegExp(this.base).source + path.source);
this._route[method].push({ fns, regex, path });
return this;
}
path = this.base + path;
Expand All @@ -120,29 +108,33 @@ class Router<Ctx extends Context = Context> {
.replace(/(\/?)\*/g, (_, p) => `(${p}.*)?`)
.replace(/\.(?=[\w(])/, "\\.");
const regex = new RegExp(`^${str}/*$`);
this._route[method].push({ fns, regex });
this._route[method].push({ fns, regex, path });
return this;
}

match(path: string, method = "GET") {
match(url: string, method = "GET") {
let fns: TRet,
params = {},
path,
j = 0,
el: TObject;
let arr = this._route[method] || [];
if (this._route["ANY"]) arr = this._route["ANY"].concat(arr);
const len = arr.length;
while (j < len) {
el = arr[j];
if (el.regex && el.regex.test(path)) {
path = decURI(path);
params = el.regex.exec(path).groups || {};
if (el.regex && el.regex.test(url)) {
try {
url = decodeURI(url);
} catch (_e) { /* noop */ }
params = el.regex.exec(url).groups || {};
fns = el.fns;
path = el.path;
break;
}
j++;
}
return { fns, params };
return { fns, params, path };
}

use(...fns: Array<Handler<Ctx>>): this;
Expand Down Expand Up @@ -186,11 +178,12 @@ class Router<Ctx extends Context = Context> {
}
}
const method = ctx.__method || (ctx.request || {}).method || "GET";
let { fns, params } = s.match(pn, method);
let { fns, params, path } = s.match(pn, method);
ctx.route = {
url: s.current,
pathname: pn,
params,
path,
} as TRet;
ctx.route.go = (url, type) => {
if (isServer) return;
Expand All @@ -207,7 +200,7 @@ class Router<Ctx extends Context = Context> {
return s.handle(s._ctx);
};
ctx.setHead = (str) => {
if (!isServer && ctx.isHydrate) {
if (!isServer) {
if (s._head) {
w.document.head.innerHTML = w.document.head.innerHTML.replace(
s._head,
Expand Down
2 changes: 1 addition & 1 deletion scripts/build.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as esbuild from "https://deno.land/x/esbuild@v0.14.25/mod.js";

const VERSION = "0.6.1";
const VERSION = "0.6.2";

const dir = Deno.cwd();
const dir_npm = dir + "/npm";
Expand Down

0 comments on commit 8ceb1dd

Please sign in to comment.