hono 0.0.6 → 0.0.10

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,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,14 +3,16 @@
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
 
11
11
  app.fire()
12
12
  ```
13
13
 
14
+ ![carbon](https://user-images.githubusercontent.com/10682/147877725-bce9bd46-953d-4d70-9c2b-3eae47ad4df9.png)
15
+
14
16
  ## Feature
15
17
 
16
18
  - Fast - the router is implemented with Trie-Tree structure.
@@ -100,32 +102,86 @@ app
100
102
  .put(() => {...})
101
103
  ```
102
104
 
105
+ ## Async
106
+
107
+ ```js
108
+ app.get('/fetch-url', async () => {
109
+ const response = await fetch('https://example.com/')
110
+ return new Response(`Status is ${response.status}`)
111
+ })
112
+ ```
113
+
103
114
  ## Middleware
104
115
 
116
+ ### Builtin Middleware
117
+
105
118
  ```js
106
- const logger = (c, next) => {
119
+ const { Hono, Middleware } = require('hono')
120
+
121
+ ...
122
+
123
+ app.use('*', Middleware.poweredBy)
124
+
125
+ ```
126
+
127
+ ### Custom Middleware
128
+
129
+ ```js
130
+ const logger = async (c, next) => {
107
131
  console.log(`[${c.req.method}] ${c.req.url}`)
108
- next()
132
+ await next()
109
133
  }
110
134
 
111
- const addHeader = (c, next) => {
112
- next()
113
- c.res.headers.add('x-message', 'This is middleware!')
135
+ const addHeader = async (c, next) => {
136
+ await next()
137
+ await c.res.headers.add('x-message', 'This is middleware!')
114
138
  }
115
139
 
116
- app = app.use('*', logger)
117
- app = app.use('/message/*', addHeader)
140
+ app.use('*', logger)
141
+ app.use('/message/*', addHeader)
118
142
 
119
143
  app.get('/message/hello', () => 'Hello Middleware!')
120
144
  ```
121
145
 
146
+ ### Custom 404 Response
147
+
148
+ ```js
149
+ const customNotFound = async (c, next) => {
150
+ await next()
151
+ if (c.res.status === 404) {
152
+ c.res = new Response('Custom 404 Not Found', { status: 404 })
153
+ }
154
+ }
155
+
156
+ app.use('*', customNotFound)
157
+ ```
158
+
159
+ ### Complex Pattern
160
+
161
+ ```js
162
+ // Log response time
163
+ app.use('*', async (c, next) => {
164
+ await next()
165
+ const responseTime = await c.res.headers.get('X-Response-Time')
166
+ console.log(`X-Response-Time: ${responseTime}`)
167
+ })
168
+
169
+ // Add X-Response-Time header
170
+ app.use('*', async (c, next) => {
171
+ const start = Date.now()
172
+ await next()
173
+ const ms = Date.now() - start
174
+ await c.res.headers.append('X-Response-Time', `${ms}ms`)
175
+ })
176
+ ```
177
+
122
178
  ## Context
123
179
 
124
180
  ### req
125
181
 
126
182
  ```js
127
183
  app.get('/hello', (c) => {
128
- const userAgent = c.req.headers('User-Agent')
184
+ const userAgent = c.req.headers.get('User-Agent')
129
185
  ...
130
186
  })
131
187
  ```
@@ -159,6 +215,69 @@ app.get('/entry/:id', (c) => {
159
215
  })
160
216
  ```
161
217
 
218
+ ## Hono in 1 minute
219
+
220
+ Create your first Cloudflare Workers with Hono from scratch.
221
+
222
+ ### Demo
223
+
224
+ ![Demo](https://user-images.githubusercontent.com/10682/147877447-ff5907cd-49be-4976-b3b4-5df2ac6dfda4.gif)
225
+
226
+ ### 1. Install Wrangler
227
+
228
+ Install Cloudflare Command Line "[Wrangler](https://github.com/cloudflare/wrangler)"
229
+
230
+ ```sh
231
+ $ npm i @cloudflare/wrangler -g
232
+ ```
233
+
234
+ ### 2. `npm init`
235
+
236
+ Make npm skeleton directory.
237
+
238
+ ```sh
239
+ $ mkdir hono-example
240
+ $ ch hono-example
241
+ $ npm init -y
242
+ ```
243
+
244
+ ### 3. `wrangler init`
245
+
246
+ Init as a wrangler project.
247
+
248
+ ```sh
249
+ $ wrangler init
250
+ ```
251
+
252
+ ### 4. `npm install hono`
253
+
254
+ Install `hono` from npm repository.
255
+
256
+ ```
257
+ $ npm i hono
258
+ ```
259
+
260
+ ### 5. Write your app
261
+
262
+ Only 4 line!!
263
+
264
+ ```js
265
+ const { Hono } = require('hono')
266
+ const app = new Hono()
267
+
268
+ app.get('/', () => new Response('Hello! Hono!'))
269
+
270
+ app.fire()
271
+ ```
272
+
273
+ ### 6. Run!
274
+
275
+ Run the development server locally.
276
+
277
+ ```sh
278
+ $ wrangler dev
279
+ ```
280
+
162
281
  ## Related projects
163
282
 
164
283
  - koa <https://github.com/koajs/koa>
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "hono",
3
- "version": "0.0.6",
4
- "description": "Minimal web framework for Cloudflare Workers",
3
+ "version": "0.0.10",
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"
@@ -13,6 +13,18 @@
13
13
  "url": "https://github.com/yusukebe/hono.git"
14
14
  },
15
15
  "homepage": "https://github.com/yusukebe/hono",
16
+ "keywords": [
17
+ "web",
18
+ "app",
19
+ "http",
20
+ "application",
21
+ "framework",
22
+ "router",
23
+ "cloudflare",
24
+ "workers",
25
+ "fastly",
26
+ "compute@edge"
27
+ ],
16
28
  "devDependencies": {
17
29
  "jest": "^27.4.5",
18
30
  "node-fetch": "^2.6.6"
package/src/compose.js CHANGED
@@ -4,8 +4,7 @@ const compose = (middleware) => {
4
4
  let index = -1
5
5
  return dispatch(0)
6
6
  function dispatch(i) {
7
- if (i <= index)
8
- return Promise.reject(new Error('next() called multiple times'))
7
+ if (i <= index) return Promise.reject(new Error('next() called multiple times'))
9
8
  index = i
10
9
  let fn = middleware[i]
11
10
  if (i === middleware.length) fn = next
@@ -3,21 +3,21 @@ const compose = require('./compose')
3
3
  describe('compose middleware', () => {
4
4
  const middleware = []
5
5
 
6
- const a = (c, next) => {
6
+ const a = async (c, next) => {
7
7
  c.req['log'] = 'log'
8
- next()
8
+ await next()
9
9
  }
10
10
  middleware.push(a)
11
11
 
12
- const b = (c, next) => {
13
- next()
12
+ const b = async (c, next) => {
13
+ await next()
14
14
  c.res['header'] = `${c.res.header}-custom-header`
15
15
  }
16
16
  middleware.push(b)
17
17
 
18
- const handler = (c, next) => {
18
+ const handler = async (c, next) => {
19
19
  c.req['log'] = `${c.req.log} message`
20
- next()
20
+ await next()
21
21
  c.res = { message: 'new response' }
22
22
  }
23
23
  middleware.push(handler)
@@ -25,17 +25,17 @@ describe('compose middleware', () => {
25
25
  const request = {}
26
26
  const response = {}
27
27
 
28
- it('Request', () => {
28
+ it('Request', async () => {
29
29
  const c = { req: request, res: response }
30
30
  const composed = compose(middleware)
31
- composed(c)
31
+ await composed(c)
32
32
  expect(c.req['log']).not.toBeNull()
33
33
  expect(c.req['log']).toBe('log message')
34
34
  })
35
- it('Response', () => {
35
+ it('Response', async () => {
36
36
  const c = { req: request, res: response }
37
37
  const composed = compose(middleware)
38
- composed(c)
38
+ await composed(c)
39
39
  expect(c.res['header']).not.toBeNull()
40
40
  expect(c.res['message']).toBe('new response')
41
41
  })
package/src/hono.d.ts ADDED
@@ -0,0 +1,67 @@
1
+ type Result = {
2
+ handler: any
3
+ params: {}
4
+ }
5
+
6
+ declare class Node {
7
+ method: string
8
+ handler: any
9
+ children: Node[]
10
+ middlewares: any[]
11
+
12
+ insert(method: string, path: string, handler: any): Node
13
+ search(method: string, path: string): Result
14
+ }
15
+
16
+ declare class Context {
17
+ req: Request
18
+ res: Response
19
+ newResponse(params: {}): Response
20
+ }
21
+
22
+ type Handler = (c: Context, next: () => void) => Response | void
23
+
24
+ declare class Router {
25
+ tempPath: string
26
+ node: Node
27
+
28
+ add(method: string, path: string, handler: Handler): Node
29
+ match(method: string, path: string): Node
30
+ }
31
+
32
+ export class Hono {
33
+ router: Router
34
+ middlewareRouters: Router[]
35
+
36
+ use(path: string, middleware: Handler): void
37
+
38
+ route(path: string): Hono
39
+ fire(): void
40
+
41
+ all(path: string, handler: Handler): Hono
42
+ get(path: string, handler: Handler): Hono
43
+ post(path: string, handler: Handler): Hono
44
+ put(path: string, handler: Handler): Hono
45
+ head(path: string, handler: Handler): Hono
46
+ delete(path: string, handler: Handler): Hono
47
+
48
+ notFound(): Response
49
+
50
+ getRouter(): Router
51
+ addRoute(method: string, args: any[]): Hono
52
+ matchRoute(method: string, path: string): Promise<Node>
53
+ createContext(req: Request, res: Response): Promise<Context>
54
+ dispatch(req: Request, res: Response): Promise<Response>
55
+ handleEvent(event: FetchEvent): Promise<Response>
56
+ }
57
+
58
+ export class Middleware {
59
+ static defaultFilter: Handler
60
+ // Add builtin middlewares
61
+ static poweredBy: Handler
62
+ }
63
+
64
+ interface FetchEvent extends Event {
65
+ request: Request
66
+ respondWith(response: Promise<Response> | Response): Promise<Response>
67
+ }
package/src/hono.js CHANGED
@@ -1,8 +1,10 @@
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')
6
8
 
7
9
  const METHOD_NAME_OF_ALL = 'ALL'
8
10
 
@@ -21,29 +23,20 @@ class Router {
21
23
  }
22
24
  }
23
25
 
24
- const getPathFromURL = (url) => {
25
- // XXX
26
- const match = url.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/)
27
- return match[5]
28
- }
29
-
30
- const proxyHandler = {
31
- get:
32
- (target, prop) =>
33
- (...args) => {
34
- if (target.constructor.prototype.hasOwnProperty(prop)) {
35
- return target[prop](...args)
36
- } else {
37
- return target.addRoute(prop, ...args)
38
- }
39
- },
40
- }
41
-
42
26
  class Hono {
43
27
  constructor() {
44
28
  this.router = new Router()
45
- this.middlewareRouter = new Router()
46
29
  this.middlewareRouters = []
30
+
31
+ for (const method of methods) {
32
+ this[method] = (...args) => {
33
+ return this.addRoute(method, ...args)
34
+ }
35
+ }
36
+ }
37
+
38
+ all(...args) {
39
+ this.addRoute('ALL', ...args)
47
40
  }
48
41
 
49
42
  getRouter() {
@@ -57,15 +50,19 @@ class Hono {
57
50
  } else {
58
51
  this.router.add(method, ...args)
59
52
  }
60
- return WrappedApp(this)
53
+ return this
61
54
  }
62
55
 
63
56
  route(path) {
64
57
  this.router.tempPath = path
65
- return WrappedApp(this)
58
+ return this
66
59
  }
67
60
 
68
61
  use(path, middleware) {
62
+ if (middleware.constructor.name !== 'AsyncFunction') {
63
+ throw new TypeError('middleware must be a async function!')
64
+ }
65
+
69
66
  const router = new Router()
70
67
  router.add(METHOD_NAME_OF_ALL, path, middleware)
71
68
  this.middlewareRouters.push(router)
@@ -90,13 +87,12 @@ class Hono {
90
87
  const [method, path] = [request.method, getPathFromURL(request.url)]
91
88
 
92
89
  const result = await this.matchRoute(method, path)
93
- if (!result) return this.notFound()
94
90
 
95
91
  request.params = (key) => result.params[key]
96
92
 
97
- let handler = result.handler[0] // XXX
93
+ let handler = result ? result.handler[0] : this.notFound // XXX
98
94
 
99
- const middleware = [defaultFilter] // add defaultFilter later
95
+ const middleware = []
100
96
 
101
97
  for (const mr of this.middlewareRouters) {
102
98
  const mwResult = mr.match(METHOD_NAME_OF_ALL, path)
@@ -106,15 +102,17 @@ class Hono {
106
102
  }
107
103
 
108
104
  let wrappedHandler = async (context, next) => {
109
- context.res = handler(context)
110
- next()
105
+ context.res = await handler(context)
106
+ await next()
111
107
  }
112
108
 
109
+ middleware.push(Middleware.defaultFilter)
113
110
  middleware.push(wrappedHandler)
111
+
114
112
  const composed = compose(middleware)
115
113
  const c = await this.createContext(request, response)
116
114
 
117
- composed(c)
115
+ await composed(c)
118
116
 
119
117
  return c.res
120
118
  }
@@ -134,8 +132,10 @@ class Hono {
134
132
  }
135
133
  }
136
134
 
137
- const WrappedApp = (hono = new Hono()) => {
138
- return new Proxy(hono, proxyHandler)
139
- }
135
+ // Default Export
136
+ module.exports = Hono
137
+ exports = module.exports
140
138
 
141
- module.exports = WrappedApp
139
+ // Named Export
140
+ exports.Hono = Hono
141
+ 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,31 +61,32 @@ 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 = async (c, next) => {
66
67
  console.log(`${c.req.method} : ${c.req.url}`)
67
- next()
68
+ await next()
68
69
  }
69
70
 
70
71
  const rootHeader = async (c, next) => {
71
- next()
72
+ await next()
72
73
  await c.res.headers.append('x-custom', 'root')
73
74
  }
74
75
 
75
76
  const customHeader = async (c, next) => {
76
- next()
77
+ await next()
77
78
  await c.res.headers.append('x-message', 'custom-header')
78
79
  }
79
80
  const customHeader2 = async (c, next) => {
80
- next()
81
- await c.res.headers.append('x-message-2', 'custom-header-2')
81
+ await next()
82
+ c.res.headers.append('x-message-2', 'custom-header-2')
82
83
  }
83
84
 
84
85
  app.use('*', logger)
85
86
  app.use('*', rootHeader)
86
87
  app.use('/hello', customHeader)
87
88
  app.use('/hello/*', customHeader2)
89
+
88
90
  app.get('/hello', () => {
89
91
  return new fetch.Response('hello')
90
92
  })
@@ -112,3 +114,45 @@ describe('Middleware', () => {
112
114
  expect(await res.headers.get('x-message-2')).toBe('custom-header-2')
113
115
  })
114
116
  })
117
+
118
+ describe('Custom 404', () => {
119
+ const app = new Hono()
120
+
121
+ const customNotFound = async (c, next) => {
122
+ await next()
123
+ if (c.res.status === 404) {
124
+ c.res = new fetch.Response('Custom 404 Not Found', { status: 404 })
125
+ }
126
+ }
127
+
128
+ app.notFound = () => {
129
+ return new fetch.Response('Default 404 Nout Found', { status: 404 })
130
+ }
131
+
132
+ app.use('*', customNotFound)
133
+ app.get('/hello', () => {
134
+ return new fetch.Response('hello')
135
+ })
136
+ it('Custom 404 Not Found', async () => {
137
+ let req = new fetch.Request('https://example.com/hello')
138
+ let res = await app.dispatch(req)
139
+ expect(res.status).toBe(200)
140
+ req = new fetch.Request('https://example.com/foo')
141
+ res = await app.dispatch(req)
142
+ expect(res.status).toBe(404)
143
+ expect(await res.text()).toBe('Custom 404 Not Found')
144
+ })
145
+ })
146
+
147
+ describe('Error Handling', () => {
148
+ const app = new Hono()
149
+
150
+ it('Middleware must be async function', () => {
151
+ expect(() => {
152
+ app.use('*', {})
153
+ }).toThrow(TypeError)
154
+ expect(() => {
155
+ app.use('*', () => '')
156
+ }).toThrow(TypeError)
157
+ })
158
+ })
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
@@ -1,13 +1,13 @@
1
- const defaultFilter = (c, next) => {
1
+ const defaultFilter = async (c, next) => {
2
2
  c.req.query = (key) => {
3
3
  const url = new URL(c.req.url)
4
4
  return url.searchParams.get(key)
5
5
  }
6
6
 
7
- next()
7
+ await next()
8
8
 
9
9
  if (typeof c.res === 'string') {
10
- c.res = new Reponse(c.res, {
10
+ c.res = new Response(c.res, {
11
11
  status: 200,
12
12
  headers: {
13
13
  'Conten-Type': 'text/plain',
@@ -0,0 +1,6 @@
1
+ const poweredBy = async (c, next) => {
2
+ await next()
3
+ await 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
+ })
@@ -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 } = 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
  })