hono 0.0.5 → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,24 @@
1
+ name: ci
2
+ on:
3
+ push:
4
+ branches: [ master ]
5
+ pull_request:
6
+ branches: [ master ]
7
+
8
+ jobs:
9
+ ci:
10
+ runs-on: ubuntu-latest
11
+
12
+ strategy:
13
+ matrix:
14
+ node-version: [16.x]
15
+ # See supported Node.js release schedule at https://nodejs.org/en/about/releases/
16
+
17
+ steps:
18
+ - uses: actions/checkout@v2
19
+ - name: Use Node.js ${{ matrix.node-version }}
20
+ uses: actions/setup-node@v2
21
+ with:
22
+ node-version: ${{ matrix.node-version }}
23
+ - run: yarn install --frozen-lockfile
24
+ - run: npm test
@@ -0,0 +1,128 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, religion, or sexual identity
10
+ and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the
26
+ overall community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or
31
+ advances of any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email
35
+ address, without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official e-mail address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ yusuke@kamawada.com.
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series
86
+ of actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or
93
+ permanent ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within
113
+ the community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.0, available at
119
+ https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120
+
121
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct
122
+ enforcement ladder](https://github.com/mozilla/diversity).
123
+
124
+ [homepage]: https://www.contributor-covenant.org
125
+
126
+ For answers to common questions about this code of conduct, see the FAQ at
127
+ https://www.contributor-covenant.org/faq. Translations are available at
128
+ https://www.contributor-covenant.org/translations.
package/README.md CHANGED
@@ -3,8 +3,8 @@
3
3
  Hono [炎] - Tiny web framework for Cloudflare Workers and others.
4
4
 
5
5
  ```js
6
- const Hono = require('Hono')
7
- const app = Hono()
6
+ const { Hono } = require('hono')
7
+ const app = new Hono()
8
8
 
9
9
  app.get('/', () => new Response('Hono!!'))
10
10
 
@@ -24,7 +24,7 @@ app.fire()
24
24
  ```
25
25
  hono x 813,001 ops/sec ±2.96% (75 runs sampled)
26
26
  itty-router x 160,415 ops/sec ±3.31% (85 runs sampled)
27
- sundar x 307,438 ops/sec ±4.77% (73 runs sampled)
27
+ sunder x 307,438 ops/sec ±4.77% (73 runs sampled)
28
28
  Fastest is hono
29
29
  ✨ Done in 37.03s.
30
30
  ```
@@ -102,6 +102,19 @@ app
102
102
 
103
103
  ## Middleware
104
104
 
105
+ ### Builtin Middleware
106
+
107
+ ```js
108
+ const { Hono, Middleware } = require('hono')
109
+
110
+ ...
111
+
112
+ app.use('*', Middleware.poweredBy)
113
+
114
+ ```
115
+
116
+ ### Custom Middleware
117
+
105
118
  ```js
106
119
  const logger = (c, next) => {
107
120
  console.log(`[${c.req.method}] ${c.req.url}`)
@@ -113,12 +126,25 @@ const addHeader = (c, next) => {
113
126
  c.res.headers.add('x-message', 'This is middleware!')
114
127
  }
115
128
 
116
- app = app.use('*', logger)
117
- app = app.use('/message/*', addHeader)
129
+ app.use('*', logger)
130
+ app.use('/message/*', addHeader)
118
131
 
119
132
  app.get('/message/hello', () => 'Hello Middleware!')
120
133
  ```
121
134
 
135
+ ### Custom 404 Response
136
+
137
+ ```js
138
+ const customNotFound = (c, next) => {
139
+ next()
140
+ if (c.res.status === 404) {
141
+ c.res = new Response('Custom 404 Not Found', { status: 404 })
142
+ }
143
+ }
144
+
145
+ app.use('*', customNotFound)
146
+ ```
147
+
122
148
  ## Context
123
149
 
124
150
  ### req
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "hono",
3
- "version": "0.0.5",
4
- "description": "Minimal web framework for Cloudflare Workers",
3
+ "version": "0.0.9",
4
+ "description": "Minimal web framework for Cloudflare Workers and Fastly Compute@Edge",
5
5
  "main": "src/hono.js",
6
6
  "scripts": {
7
7
  "test": "jest"
@@ -17,4 +17,4 @@
17
17
  "jest": "^27.4.5",
18
18
  "node-fetch": "^2.6.6"
19
19
  }
20
- }
20
+ }
package/src/hono.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ declare class FetchEvent {}
2
+ declare class Request {}
3
+ declare class Response {}
4
+ declare class Context {}
5
+
6
+ declare class Node {}
7
+
8
+ declare class Router {
9
+ tempPath: string
10
+ node: Node
11
+
12
+ add(method: string, path: string, handlers: any[]): Node
13
+ match(method: string, path: string): Node
14
+ }
15
+
16
+ export class Hono {
17
+ router: Router
18
+ middlewareRouters: Router[]
19
+
20
+ getRouter(): Router
21
+ addRoute(method: string, args: any[]): Hono
22
+ matchRoute(method: string, path: string): Node
23
+ createContext(req: Request, res: Response): Context
24
+ dispatch(req: Request, res: Response): Response
25
+ handleEvent(event: FetchEvent): Response
26
+ fire(): void
27
+
28
+ notFound(): Response
29
+
30
+ route(path: string): Hono
31
+
32
+ use(path: string, middleware: any): void
33
+
34
+ all(path: string, handler: any): Hono
35
+ get(path: string, handler: any): Hono
36
+ post(path: string, handler: any): Hono
37
+ put(path: string, handler: any): Hono
38
+ head(path: string, handler: any): Hono
39
+ delete(path: string, handler: any): Hono
40
+ }
41
+
42
+ // XXX
43
+ declare interface BuiltinMiddleware {}
44
+
45
+ export class Middleware {
46
+ static defaultFilter: BuiltinMiddleware
47
+ static poweredBy: BuiltinMiddleware
48
+ }
package/src/hono.js CHANGED
@@ -1,8 +1,12 @@
1
1
  'use strict'
2
2
 
3
3
  const Node = require('./node')
4
+ const Middleware = require('./middleware')
4
5
  const compose = require('./compose')
5
- const defaultFilter = require('./middleware/defaultFilter')
6
+ const methods = require('./methods')
7
+ const { getPathFromURL } = require('./util')
8
+
9
+ const METHOD_NAME_OF_ALL = 'ALL'
6
10
 
7
11
  class Router {
8
12
  constructor() {
@@ -19,33 +23,24 @@ class Router {
19
23
  }
20
24
  }
21
25
 
22
- const getPathFromURL = (url) => {
23
- // XXX
24
- const match = url.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/)
25
- return match[5]
26
- }
27
-
28
26
  class Hono {
29
27
  constructor() {
30
28
  this.router = new Router()
31
- this.middlewareRouter = new Router()
32
29
  this.middlewareRouters = []
33
- }
34
30
 
35
- get(...args) {
36
- return this.addRoute('GET', ...args)
37
- }
38
- post(...args) {
39
- return this.addRoute('POST', ...args)
40
- }
41
- put(...args) {
42
- return this.addRoute('PUT', ...args)
31
+ for (const method of methods) {
32
+ this[method] = (...args) => {
33
+ return this.addRoute(method, ...args)
34
+ }
35
+ }
43
36
  }
44
- delete(...args) {
45
- return this.addRoute('DELETE', ...args)
37
+
38
+ all(...args) {
39
+ this.addRoute('ALL', ...args)
46
40
  }
47
- patch(...args) {
48
- return this.addRoute('PATCH', ...args)
41
+
42
+ getRouter() {
43
+ return this.router
49
44
  }
50
45
 
51
46
  addRoute(method, ...args) {
@@ -58,24 +53,23 @@ class Hono {
58
53
  return this
59
54
  }
60
55
 
61
- getRouter() {
62
- return this.router
63
- }
64
-
65
56
  route(path) {
66
57
  this.router.tempPath = path
67
58
  return this
68
59
  }
69
60
 
70
61
  use(path, middleware) {
62
+ if (middleware.constructor.name !== 'Function') {
63
+ throw new TypeError('middleware must be a function!')
64
+ }
65
+
71
66
  const router = new Router()
72
- router.add('all', path, middleware)
67
+ router.add(METHOD_NAME_OF_ALL, path, middleware)
73
68
  this.middlewareRouters.push(router)
74
69
  }
75
70
 
76
71
  async matchRoute(method, path) {
77
- const res = this.router.match(method, path)
78
- return res
72
+ return this.router.match(method, path)
79
73
  }
80
74
 
81
75
  // XXX
@@ -93,16 +87,15 @@ class Hono {
93
87
  const [method, path] = [request.method, getPathFromURL(request.url)]
94
88
 
95
89
  const result = await this.matchRoute(method, path)
96
- if (!result) return this.notFound()
97
90
 
98
91
  request.params = (key) => result.params[key]
99
92
 
100
- let handler = result.handler[0] // XXX
93
+ let handler = result ? result.handler[0] : this.notFound // XXX
101
94
 
102
- const middleware = [defaultFilter] // add defaultFilter later
95
+ const middleware = [Middleware.defaultFilter] // add defaultFilter later
103
96
 
104
97
  for (const mr of this.middlewareRouters) {
105
- const mwResult = mr.match('all', path)
98
+ const mwResult = mr.match(METHOD_NAME_OF_ALL, path)
106
99
  if (mwResult) {
107
100
  middleware.push(...mwResult.handler)
108
101
  }
@@ -137,8 +130,10 @@ class Hono {
137
130
  }
138
131
  }
139
132
 
140
- const CreateApp = () => {
141
- return new Hono()
142
- }
133
+ // Default Export
134
+ module.exports = Hono
135
+ exports = module.exports
143
136
 
144
- module.exports = CreateApp
137
+ // Named Export
138
+ exports.Hono = Hono
139
+ exports.Middleware = Middleware
package/src/hono.test.js CHANGED
@@ -1,8 +1,9 @@
1
- const Hono = require('./hono')
2
1
  const fetch = require('node-fetch')
2
+ const { Hono } = require('./hono')
3
3
 
4
4
  describe('GET Request', () => {
5
- const app = Hono()
5
+ const app = new Hono()
6
+
6
7
  app.get('/hello', () => {
7
8
  return new fetch.Response('hello', {
8
9
  status: 200,
@@ -29,7 +30,7 @@ describe('GET Request', () => {
29
30
  })
30
31
 
31
32
  describe('params and query', () => {
32
- const app = Hono()
33
+ const app = new Hono()
33
34
 
34
35
  app.get('/entry/:id', async (c) => {
35
36
  const id = await c.req.params('id')
@@ -60,29 +61,94 @@ describe('params and query', () => {
60
61
  })
61
62
 
62
63
  describe('Middleware', () => {
63
- const app = Hono()
64
+ const app = new Hono()
64
65
 
65
66
  const logger = (c, next) => {
66
67
  console.log(`${c.req.method} : ${c.req.url}`)
67
68
  next()
68
69
  }
69
70
 
71
+ const rootHeader = (c, next) => {
72
+ next()
73
+ c.res.headers.append('x-custom', 'root')
74
+ }
75
+
70
76
  const customHeader = (c, next) => {
71
77
  next()
72
78
  c.res.headers.append('x-message', 'custom-header')
73
79
  }
80
+ const customHeader2 = (c, next) => {
81
+ next()
82
+ c.res.headers.append('x-message-2', 'custom-header-2')
83
+ }
74
84
 
75
85
  app.use('*', logger)
86
+ app.use('*', rootHeader)
76
87
  app.use('/hello', customHeader)
88
+ app.use('/hello/*', customHeader2)
77
89
  app.get('/hello', () => {
78
90
  return new fetch.Response('hello')
79
91
  })
92
+ app.get('/hello/:message', (c) => {
93
+ const message = c.req.params('message')
94
+ return new fetch.Response(`${message}`)
95
+ })
80
96
 
81
97
  it('logging and custom header', async () => {
82
98
  let req = new fetch.Request('https://example.com/hello')
83
99
  let res = await app.dispatch(req)
84
100
  expect(res.status).toBe(200)
85
101
  expect(await res.text()).toBe('hello')
102
+ expect(await res.headers.get('x-custom')).toBe('root')
86
103
  expect(await res.headers.get('x-message')).toBe('custom-header')
104
+ expect(await res.headers.get('x-message-2')).toBe('custom-header-2')
105
+ })
106
+
107
+ it('logging and custom header with named params', async () => {
108
+ let req = new fetch.Request('https://example.com/hello/message')
109
+ let res = await app.dispatch(req)
110
+ expect(res.status).toBe(200)
111
+ expect(await res.text()).toBe('message')
112
+ expect(await res.headers.get('x-custom')).toBe('root')
113
+ expect(await res.headers.get('x-message-2')).toBe('custom-header-2')
114
+ })
115
+ })
116
+
117
+ describe('Custom 404', () => {
118
+ const app = new Hono()
119
+
120
+ const customNotFound = (c, next) => {
121
+ next()
122
+ if (c.res.status === 404) {
123
+ c.res = new fetch.Response('Custom 404 Not Found', { status: 404 })
124
+ }
125
+ }
126
+
127
+ app.notFound = () => {
128
+ return new fetch.Response('Default 404 Nout Found', { status: 404 })
129
+ }
130
+
131
+ app.use('*', customNotFound)
132
+ app.get('/hello', () => {
133
+ return new fetch.Response('hello')
134
+ })
135
+ it('Custom 404 Not Found', async () => {
136
+ let req = new fetch.Request('https://example.com/hello')
137
+ let res = await app.dispatch(req)
138
+ expect(res.status).toBe(200)
139
+ req = new fetch.Request('https://example.com/foo')
140
+ res = await app.dispatch(req)
141
+ expect(res.status).toBe(404)
142
+ expect(await res.text()).toBe('Custom 404 Not Found')
143
+ })
144
+ })
145
+
146
+ describe('Error Handling', () => {
147
+ const app = new Hono()
148
+
149
+ it('Middleware must be function', () => {
150
+ expect(() => {
151
+ app.use('*', {})
152
+ }).toThrow(TypeError)
87
153
  })
88
154
  })
package/src/methods.js ADDED
@@ -0,0 +1,30 @@
1
+ const methods = [
2
+ 'get',
3
+ 'post',
4
+ 'put',
5
+ 'head',
6
+ 'delete',
7
+ 'options',
8
+ 'trace',
9
+ 'copy',
10
+ 'lock',
11
+ 'mkcol',
12
+ 'move',
13
+ 'patch',
14
+ 'purge',
15
+ 'propfind',
16
+ 'proppatch',
17
+ 'unlock',
18
+ 'report',
19
+ 'mkactivity',
20
+ 'checkout',
21
+ 'merge',
22
+ 'm-search',
23
+ 'notify',
24
+ 'subscribe',
25
+ 'unsubscribe',
26
+ 'search',
27
+ 'connect',
28
+ ]
29
+
30
+ module.exports = methods
@@ -0,0 +1,6 @@
1
+ const poweredBy = (c, next) => {
2
+ next()
3
+ c.res.headers.append('X-Powered-By', 'Hono')
4
+ }
5
+
6
+ module.exports = poweredBy
@@ -0,0 +1,17 @@
1
+ const fetch = require('node-fetch')
2
+ const { Hono, Middleware } = require('../hono')
3
+
4
+ describe('Powered by Middleware', () => {
5
+ const app = new Hono()
6
+
7
+ app.use('*', Middleware.poweredBy)
8
+ app.get('/', () => new fetch.Response('root'))
9
+
10
+ it('Response headers include X-Powered-By', async () => {
11
+ let req = new fetch.Request('https://example.com/')
12
+ let res = await app.dispatch(req, new fetch.Response())
13
+ expect(res).not.toBeNull()
14
+ expect(res.status).toBe(200)
15
+ expect(res.headers.get('X-Powered-By')).toBe('Hono')
16
+ })
17
+ })
@@ -0,0 +1,9 @@
1
+ const defaultFilter = require('./middleware/defaultFilter')
2
+ const poweredBy = require('./middleware/poweredBy')
3
+
4
+ function Middleware() {}
5
+
6
+ Middleware.defaultFilter = defaultFilter
7
+ Middleware.poweredBy = poweredBy
8
+
9
+ module.exports = Middleware
@@ -0,0 +1,17 @@
1
+ const fetch = require('node-fetch')
2
+ const { Hono, Middleware } = require('./hono')
3
+
4
+ describe('Builtin Middleware', () => {
5
+ const app = new Hono()
6
+
7
+ app.use('*', Middleware.poweredBy)
8
+ app.get('/', () => new fetch.Response('root'))
9
+
10
+ it('Builtin Powered By Middleware', async () => {
11
+ let req = new fetch.Request('https://example.com/')
12
+ let res = await app.dispatch(req, new fetch.Response())
13
+ expect(res).not.toBeNull()
14
+ expect(res.status).toBe(200)
15
+ expect(res.headers.get('X-Powered-By')).toBe('Hono')
16
+ })
17
+ })
package/src/node.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  const { splitPath, getPattern } = require('./util')
4
4
 
5
- const METHOD_NAME_OF_ALL = 'all'
5
+ const METHOD_NAME_OF_ALL = 'ALL'
6
6
 
7
7
  const createResult = (handler, params) => {
8
8
  return { handler: handler, params: params }
@@ -18,6 +18,7 @@ function Node(method, handler, children) {
18
18
  if (method && handler) {
19
19
  this.method[method] = handler
20
20
  }
21
+ this.middlewares = []
21
22
  }
22
23
 
23
24
  Node.prototype.insert = function (method, path, handler) {
@@ -50,6 +51,7 @@ Node.prototype.search = function (method, path) {
50
51
  continue
51
52
  }
52
53
 
54
+ let isWildcard = false
53
55
  let isParamMatch = false
54
56
  const keys = Object.keys(curNode.children)
55
57
  for (let j = 0; j < keys.length; j++) {
@@ -57,7 +59,7 @@ Node.prototype.search = function (method, path) {
57
59
  // Wildcard
58
60
  if (key === '*') {
59
61
  curNode = curNode.children['*']
60
- isParamMatch = true
62
+ isWildcard = true
61
63
  break
62
64
  }
63
65
  const pattern = getPattern(key)
@@ -74,6 +76,10 @@ Node.prototype.search = function (method, path) {
74
76
  }
75
77
  }
76
78
 
79
+ if (isWildcard) {
80
+ break
81
+ }
82
+
77
83
  if (isParamMatch === false) {
78
84
  return noRoute()
79
85
  }
package/src/node.test.js CHANGED
@@ -123,7 +123,7 @@ describe('Regexp', () => {
123
123
 
124
124
  describe('All', () => {
125
125
  const node = new Node()
126
- node.insert('all', '/all-methods', 'all methods')
126
+ node.insert('ALL', '/all-methods', 'all methods') // ALL
127
127
  it('/all-methods', () => {
128
128
  res = node.search('get', '/all-methods')
129
129
  expect(res).not.toBeNull()
@@ -1,7 +1,7 @@
1
- const App = require('./hono')
1
+ const { Hono } = require('./hono')
2
2
 
3
3
  describe('Basic Usage', () => {
4
- const router = App()
4
+ const router = new Hono()
5
5
 
6
6
  it('get, post hello', async () => {
7
7
  router.get('/hello', 'get hello')
@@ -24,7 +24,7 @@ describe('Basic Usage', () => {
24
24
  })
25
25
 
26
26
  describe('Complex', () => {
27
- let router = App()
27
+ let router = new Hono()
28
28
 
29
29
  it('Named Param', async () => {
30
30
  router.get('/entry/:id', 'get entry')
@@ -56,7 +56,7 @@ describe('Complex', () => {
56
56
  })
57
57
 
58
58
  describe('Chained Route', () => {
59
- let router = App()
59
+ let router = new Hono()
60
60
 
61
61
  it('Return rooter object', async () => {
62
62
  router = router.patch('/hello', 'patch hello')
package/src/util.js CHANGED
@@ -20,7 +20,14 @@ const getPattern = (label) => {
20
20
  }
21
21
  }
22
22
 
23
+ const getPathFromURL = (url) => {
24
+ // XXX
25
+ const match = url.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/)
26
+ return match[5]
27
+ }
28
+
23
29
  module.exports = {
24
30
  splitPath,
25
31
  getPattern,
32
+ getPathFromURL,
26
33
  }
package/src/util.test.js CHANGED
@@ -1,4 +1,4 @@
1
- const { splitPath, getPattern, getParamName } = require('./util')
1
+ const { splitPath, getPattern, getPathFromURL } = require('./util')
2
2
 
3
3
  describe('Utility methods', () => {
4
4
  it('splitPath', () => {
@@ -26,4 +26,19 @@ describe('Utility methods', () => {
26
26
  expect(res[0]).toBe('id')
27
27
  expect(res[1]).toBe('([0-9]+)')
28
28
  })
29
+
30
+ it('getPathFromURL', () => {
31
+ let path = getPathFromURL('https://example.com/')
32
+ expect(path).toBe('/')
33
+ path = getPathFromURL('https://example.com/hello')
34
+ expect(path).toBe('/hello')
35
+ path = getPathFromURL('https://example.com/hello/hey')
36
+ expect(path).toBe('/hello/hey')
37
+ path = getPathFromURL('https://example.com/hello?name=foo')
38
+ expect(path).toBe('/hello')
39
+ path = getPathFromURL('https://example.com/hello/hey?name=foo&name=bar')
40
+ expect(path).toBe('/hello/hey')
41
+ path = getPathFromURL('https://example.com/hello/hey#fragment')
42
+ expect(path).toBe('/hello/hey')
43
+ })
29
44
  })