# route-path-match - 路由路径匹配

#### 安装

```shell
npm i -D route-path-match
# or
pnpm add -D route-path-match
```

## 路径匹配示例

```js
import parsePathTplToMatch from "route-path-match";
const matchParams = parsePathTplToMatch("/:group/:id");
const params = matchParams("/items/aaa");
if (params) {
  console.log("path matched", params);
  // params -> { group: 'items', id: 'aaa' }
} else {
  console.log("path unmatch");
}
```

#### 路径模板规则

- 其中 `(` `)` `?` 等 3 个字符为正则的含义及用法，即分组与可选
- 变量使用形如 `:id` 或 `::filePath` 即以 `:`开头的变量名，前者匹配除 `/` 之外的字符，后者匹配任意字符
- 指定变量的正则形如 `:id<[0-9]+|all>` 其中 `<` `>` 包裹的内容会被识别为该变量的正则表达式。其中的反斜杠需要转义，如 `\\d+`
- 变量名只支持 `驼峰形式`，比如 :_groupId_
- 路径模板使用变量时，会转换为正则，否则作字符串全等匹配

#### 路径模板示例

- /assets/::filePath
- /:group/:id
- /:group/:id<[0-9]+>
- /:group/:id<[0-9]+>(:extname<.html|.xml>)?
- /:group/:id?
- /:group(/:id)?
- /:group<items|users|images>(/:id)?

## 路由匹配示例

```js
import { ExpressRouter } from "route-path-match/server";
const notFound = async (req, res) => {
  res.end('not found')
}
const resolvePage = async (req, res) => {
  res.end('some page html')
}
const initDb = async (req, res) => {
  req.db = 'some db connection'
}

const routes = [
  {
    method: 'OPTIONS',
    path: '*',
    response: ''
  },
  {
    path: '/pages/1',
    handler: [ initDb, resolvePage ]
  },
  {
    path: *,
    handler: notFound
  }
];
const router = new ExpressRouter(routes);

import express from 'express'
const app = express()
app.use((req, res) => router.handle(req, res))
app.listen(8080)
```
