Skip to content
Myr

Can use async on handler (#16)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Yusuke Wada · committed by GitHub · parent 5db6179 · Browse files · 9 files+116 added−63 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

9 files+116 added−63 removed

  • tests:+27 added−23 removed
  • other:+89 added−40 removed

9 files+116 added−63 removed

modified:example/basic/index.js+34 added-15 removed
modified:src/middleware/defaultFilter.js+3 added-3 removed
modified:src/middleware/poweredBy.js+3 added-3 removed
modified:src/compose.js+1 added-2 removed
modified:src/compose.test.js+10 added-10 removed
modified:src/hono.d.ts+5 added-4 removed
1declare interface FetchEvent {}2declare interface Request {}3declare interface Response {}41type Result = {2 handler: any3 params: {}4}
54 unmodified lines
59 static defaultFilter: Handler60 // Add builtin middlewares61 static poweredBy: Handler62}6364interface FetchEvent extends Event {65 request: Request66 respondWith(response: Promise<Response> | Response): Promise<Response>67}
modified:src/hono.js+8 added-6 removed
57 unmodified lines
58 return this59 }6061 use(path, middleware) {62 if (middleware.constructor.name !== 'Function') {63 throw new TypeError('middleware must be a function!')62 if (middleware.constructor.name !== 'AsyncFunction') {63 throw new TypeError('middleware must be a async function!')64 }6566 const router = new Router()67 router.add(METHOD_NAME_OF_ALL, path, middleware)
23 unmodified lines
91 request.params = (key) => result.params[key]9293 let handler = result ? result.handler[0] : this.notFound // XXX9495 const middleware = [Middleware.defaultFilter] // add defaultFilter later95 const middleware = []9697 for (const mr of this.middlewareRouters) {98 const mwResult = mr.match(METHOD_NAME_OF_ALL, path)99 if (mwResult) {
1 unmodified line
101 }102 }103104 let wrappedHandler = async (context, next) => {105 context.res = handler(context)106 next()105 context.res = await handler(context)106 await next()107 }108109 middleware.push(Middleware.defaultFilter)110 middleware.push(wrappedHandler)111112 const composed = compose(middleware)113 const c = await this.createContext(request, response)114113 composed(c)115 await composed(c)116117 return c.res118 }119
22 unmodified lines
modified:src/hono.test.js+17 added-13 removed
61 unmodified lines
6263describe('Middleware', () => {64 const app = new Hono()6566 const logger = (c, next) => {66 const logger = async (c, next) => {67 console.log(`${c.req.method} : ${c.req.url}`)68 next()68 await next()69 }7071 const rootHeader = (c, next) => {72 next()73 c.res.headers.append('x-custom', 'root')71 const rootHeader = async (c, next) => {72 await next()73 await c.res.headers.append('x-custom', 'root')74 }7576 const customHeader = (c, next) => {77 next()78 c.res.headers.append('x-message', 'custom-header')76 const customHeader = async (c, next) => {77 await next()78 await c.res.headers.append('x-message', 'custom-header')79 }80 const customHeader2 = (c, next) => {81 next()80 const customHeader2 = async (c, next) => {81 await next()82 c.res.headers.append('x-message-2', 'custom-header-2')83 }8485 app.use('*', logger)86 app.use('*', rootHeader)87 app.use('/hello', customHeader)88 app.use('/hello/*', customHeader2)8990 app.get('/hello', () => {91 return new fetch.Response('hello')92 })93 app.get('/hello/:message', (c) => {
23 unmodified lines
117118describe('Custom 404', () => {119 const app = new Hono()120120 const customNotFound = (c, next) => {121 next()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 }
19 unmodified lines
146147describe('Error Handling', () => {148 const app = new Hono()149149 it('Middleware must be function', () => {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})
modified:README.md+35 added-7 removed
100 unmodified lines
101 .post(() => {...})102 .put(() => {...})103```104105## Async106107```js108app.get('/fetch-url', async () => {109 const response = await fetch('https://example.com/')110 return new Response(`Status is ${response.status}`)111})112```113114## Middleware115116### Builtin Middleware117
8 unmodified lines
126127### Custom Middleware128129```js121const logger = (c, next) => {130const logger = async (c, next) => {131 console.log(`[${c.req.method}] ${c.req.url}`)123 next()132 await next()133}134126const addHeader = (c, next) => {127 next()128 c.res.headers.add('x-message', 'This is middleware!')135const addHeader = async (c, next) => {136 await next()137 await c.res.headers.add('x-message', 'This is middleware!')138}139140app.use('*', logger)141app.use('/message/*', addHeader)
3 unmodified lines
145146### Custom 404 Response147148```js140const customNotFound = (c, next) => {141 next()149const 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}155156app.use('*', customNotFound)157```158159### Complex Pattern160161```js162// Log response time163app.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})168169// Add X-Response-Time header170app.use('*', async (c, next) => {171 const start = Date.now()172 await next()173 const ms = Date.now() - start174 await c.res.headers.append('X-Response-Time', `${ms}ms`)175})176```177178## Context179180### req181
115 unmodified lines