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
Provenance
- Commit
303db32- Tree
68bfda9- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
5db6179
9 files changed+116 added−63 removed
modified:example/basic/index.js+34 added-15 removed
112345678910111213456171878910111213141516171819202122232425262728293022313224333435363738394041424344454647484950const { Hono, Middleware } = require('hono')const { Hono, Middleware } = require('../../src/hono')const app = new Hono()
// Custom Middlewareconst logger = (c, next) => { console.log(`[${c.req.method}] ${c.req.url}`) next()}const addHeader = (c, next) => { next() c.res.headers.append('X-message', 'This is addHeader middleware!')}
// Mount Builtin Middlewareapp.use('*', Middleware.poweredBy)
// Mount Custom middlewareapp.use('*', logger)// Custom Middleware// Add Custom Headerconst addHeader = async (c, next) => { await next() await c.res.headers.append('X-message', 'This is addHeader middleware!')}app.use('/hello/*', addHeader)
// Log response timeapp.use('*', async (c, next) => { await next() const responseTime = await c.res.headers.get('X-Response-Time') console.log(`X-Response-Time: ${responseTime}`)})
// Add X-Response-Time headerapp.use('*', async (c, next) => { const start = Date.now() await next() const ms = Date.now() - start await c.res.headers.append('X-Response-Time', `${ms}ms`)})
// Routingapp.get('/', () => new Response('Hono!!'))app.get('/', () => 'Hono!!')app.get('/hello', () => new Response('This is /hello'))
app.get('/entry/:id', (c) => { const id = c.req.params('id') return new Response(`Your ID is ${id}`)})
// Asyncapp.get('/fetch-url', async () => { const response = await fetch('https://example.com/') return new Response(`https://example.com/ is ${response.status}`)})
app.get('/user-agent', (c) => { const userAgent = c.req.headers.get('User-Agent') return new Response(`Your UserAgent is ${userAgent}`)})
// addEventListenerapp.fire()modified:src/middleware/defaultFilter.js+3 added-3 removed
112345677891010111213145 unmodified linesconst defaultFilter = (c, next) => {const defaultFilter = async (c, next) => { c.req.query = (key) => { const url = new URL(c.req.url) return url.searchParams.get(key) }
next() await next()
if (typeof c.res === 'string') { c.res = new Reponse(c.res, { c.res = new Response(c.res, { status: 200, headers: { 'Conten-Type': 'text/plain', },5 unmodified linesmodified:src/middleware/poweredBy.js+3 added-3 removed
123123456const poweredBy = (c, next) => { next() c.res.headers.append('X-Powered-By', 'Hono')const poweredBy = async (c, next) => { await next() await c.res.headers.append('X-Powered-By', 'Hono')}
module.exports = poweredBymodified:src/compose.js+1 added-2 removed
2 unmodified lines345678789101110 unmodified lines2 unmodified lines return function (context, next) { let index = -1 return dispatch(0) function dispatch(i) { if (i <= index) return Promise.reject(new Error('next() called multiple times')) if (i <= index) return Promise.reject(new Error('next() called multiple times')) index = i let fn = middleware[i] if (i === middleware.length) fn = next if (!fn) return Promise.resolve()10 unmodified linesmodified:src/compose.test.js+10 added-10 removed
123456678891011121312131415161718181920202122232425262728282930313132333435353637383839404142const compose = require('./compose')
describe('compose middleware', () => { const middleware = []
const a = (c, next) => { const a = async (c, next) => { c.req['log'] = 'log' next() await next() } middleware.push(a)
const b = (c, next) => { next() const b = async (c, next) => { await next() c.res['header'] = `${c.res.header}-custom-header` } middleware.push(b)
const handler = (c, next) => { const handler = async (c, next) => { c.req['log'] = `${c.req.log} message` next() await next() c.res = { message: 'new response' } } middleware.push(handler)
const request = {} const response = {}
it('Request', () => { it('Request', async () => { const c = { req: request, res: response } const composed = compose(middleware) composed(c) await composed(c) expect(c.req['log']).not.toBeNull() expect(c.req['log']).toBe('log message') }) it('Response', () => { it('Response', async () => { const c = { req: request, res: response } const composed = compose(middleware) composed(c) await composed(c) expect(c.res['header']).not.toBeNull() expect(c.res['message']).toBe('new response') })})modified:src/hono.d.ts+5 added-4 removed
1-declare interface FetchEvent {}2-declare interface Request {}3-declare interface Response {}4-1 type Result = {2 handler: any3 params: {}4 }54 unmodified lines59 static defaultFilter: Handler60 // Add builtin middlewares61 static poweredBy: Handler62 }63+64+interface FetchEvent extends Event {65+ request: Request66+ respondWith(response: Promise<Response> | Response): Promise<Response>67+}modified:src/hono.js+8 added-6 removed
57 unmodified lines58 return this59 }60 61 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 }65 66 const router = new Router()67 router.add(METHOD_NAME_OF_ALL, path, middleware)23 unmodified lines91 request.params = (key) => result.params[key]92 93 let handler = result ? result.handler[0] : this.notFound // XXX94 95- const middleware = [Middleware.defaultFilter] // add defaultFilter later95+ const middleware = []96 97 for (const mr of this.middlewareRouters) {98 const mwResult = mr.match(METHOD_NAME_OF_ALL, path)99 if (mwResult) {1 unmodified line101 }102 }103 104 let wrappedHandler = async (context, next) => {105- context.res = handler(context)106- next()105+ context.res = await handler(context)106+ await next()107 }108 109+ middleware.push(Middleware.defaultFilter)110 middleware.push(wrappedHandler)111+112 const composed = compose(middleware)113 const c = await this.createContext(request, response)114 113- composed(c)115+ await composed(c)116 117 return c.res118 }119 22 unmodified linesmodified:src/hono.test.js+17 added-13 removed
61 unmodified lines62 63 describe('Middleware', () => {64 const app = new Hono()65 66- 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 }70 71- 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 }75 76- 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 }84 85 app.use('*', logger)86 app.use('*', rootHeader)87 app.use('/hello', customHeader)88 app.use('/hello/*', customHeader2)89+90 app.get('/hello', () => {91 return new fetch.Response('hello')92 })93 app.get('/hello/:message', (c) => {23 unmodified lines117 118 describe('Custom 404', () => {119 const app = new Hono()120 120- 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 lines146 147 describe('Error Handling', () => {148 const app = new Hono()149 149- 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 lines101 .post(() => {...})102 .put(() => {...})103 ```104 105+## Async106+107+```js108+app.get('/fetch-url', async () => {109+ const response = await fetch('https://example.com/')110+ return new Response(`Status is ${response.status}`)111+})112+```113+114 ## Middleware115 116 ### Builtin Middleware117 8 unmodified lines126 127 ### Custom Middleware128 129 ```js121-const logger = (c, next) => {130+const logger = async (c, next) => {131 console.log(`[${c.req.method}] ${c.req.url}`)123- next()132+ await next()133 }134 126-const addHeader = (c, next) => {127- next()128- 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!')138 }139 140 app.use('*', logger)141 app.use('/message/*', addHeader)3 unmodified lines145 146 ### Custom 404 Response147 148 ```js140-const customNotFound = (c, next) => {141- next()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 Pattern160+161+```js162+// Log response time163+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 header170+app.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+```177+178 ## Context179 180 ### req181 115 unmodified lines