Skip to content
Myr

Middlewares works!

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

authored by Yusuke Wada · committed by Yusuke Wada · parent d13401f · Browse files · 8 files+172 added−86 removed
This commit

State

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

Diff stats

8 files+172 added−86 removed

  • tests:+60 added−14 removed
  • other:+112 added−72 removed

8 files+172 added−86 removed

modified:example/basic/index.js+9 added-4 removed
added:src/middleware/filter.js+19 added
deleted:src/middleware/request.js-17 removed
added:src/compose.js+22 added
added:src/compose.test.js+42 added
modified:src/hono.js+21 added-32 removed
1'use strict'23const Node = require('./node')4const compose = require('./compose')2const filter = require('./middleware/request')5const filter = require('./middleware/filter')67class Router {8 constructor() {9 this.node = new Node()
24 unmodified lines
34 }35 },36}3735// Based on the code in the MIT licensed `koa-compose` package.36const compose = (middleware) => {37 return function (req, res, next) {38 let index = -139 return dispatch(0)40 function dispatch(i) {41 if (i <= index)42 return Promise.reject(new Error('next() called multiple times'))43 index = i44 let fn = middleware[i]45 if (i === middleware.length) fn = next46 if (!fn) return Promise.resolve()47 try {48 return Promise.resolve(fn(req, res, dispatch.bind(null, i + 1)))49 } catch (err) {50 return Promise.reject(err)51 }52 }53 }54}5538class App {39 constructor() {40 this.router = new Router()41 this.middlewareRouter = new Router()42 this.middleware = []43 }4445 addRoute(method, path, ...args) {46 this.router.add(method, path, ...args)
17 unmodified lines
64 }65 this.middlewareRouter.add('all', path, ...middleware)66 }6768 // XXX69 createContext(req, res) {70 return { req: req, res: res }71 }7273 async dispatch(request, response) {74 const url = new URL(request.url)75 const [method, path] = [request.method, url.pathname]76
9 unmodified lines
86 }8788 let handler89 for (const resultHandler of result.handler) {90 if (resultHandler) {102 handler = resultHandler91 handler = resultHandler92 }93 }94105 /*106 middleware.push((req, res, next) => {107 handler(req, res)95 let wrappedHandler = (context, next) => {96 context.res = handler(context)97 next()109 })110 */98 }99100 middleware.push(wrappedHandler)101 const composed = compose(middleware)113 composed(request, response)114 response = await handler(request, response)115 composed(request, response)102 const c = this.createContext(request, response)103117 return response104 composed(c)105106 return c.res107 }108109 async handleEvent(event) {110 return await this.dispatch(event.request, new Response())
18 unmodified lines
modified:src/hono.test.js+18 added-14 removed
modified:README.md+41 added-19 removed
13 unmodified lines
1415- Fast - the router is implemented with Trie-Tree structure.16- Tiny - use only standard API.17- Portable - zero dependencies.18- Flexible - you can make your own middlewares.18- Optimized for Cloudflare Workers.19- Optimized - for Cloudflare Workers.2021## Install2223```
23 unmodified lines
47// HTTP Methods48app.get('/', () => new Response('GET /'))49app.post('/', () => new Response('POST /'))505051// Wildcard52app.get('/wild/*/card', => {52app.get('/wild/*/card', () => {53 return new Reponse('GET /wild/*/card')54})55```56
6 unmodified lines
6364### Named Parameter6566```js67app.get('/user/:name', (req) => {68 const name = req.params('name')67app.get('/user/:name', (c) => {68 const name = c.req.params('name')69 ...70})71```7273### Regexp7475```js76app.get('/post/:date{[0-9]+}/:title{[a-z]+}', (req) => {77 const date = req.params('date')78 const title = req.params('title')76app.get('/post/:date{[0-9]+}/:title{[a-z]+}', (c) => {77 const date = c.req.params('date')78 const title = c.req.params('title')79 ...80```8182### Chained Route8384```js85app86 .route('/api/book')87 .get(() => {...})88 .post(() => {...})89 .put(() => {...})87 .get(() => {...})88 .post(() => {...})89 .put(() => {...})90```9192## Middleware9394```js95const logger = (req, res, next) => {96 console.log(`[${req.method}] ${req.url}`)95const logger = (c, next) => {96 console.log(`[${c.req.method}] ${c.req.url}`)97 next()98}99100const addHeader = (req, res, next) => {100const addHeader = (c, next) => {101 next()102 res.headers.add('x-message', 'This is middleware!')102 c.res.headers.add('x-message', 'This is middleware!')103}104105app = app.use('*', logger)106app = app.use('/message/*', addHeader)107108app.get('/message/hello', () => 'Hello Middleware!')109```110111## Context112113### req114115```js116app.get('/hello', (c) => {117 const userAgent = c.req.headers('User-Agent')118 ...119})120```121122### res123124```js125app.use('/', (c, next) => {126 next()127 c.res.headers.append('X-Debug', 'Debug message')128})129```130131## Request132133### query134135```js116app.get('/search', (req) => {117 const query = req.query('q')136app.get('/search', (c) => {137 const query = c.req.query('q')138 ...139})140```141142### params143144```js124app.get('/entry/:id', (req) => {125 const id = req.params('id')145app.get('/entry/:id', (c) => {146 const id = c.req.params('id')147 ...148})149```150151## Related projects
14 unmodified lines