Skip to content
Myr

Merge pull request #239 from honojs/develop

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

for v1.3.0

authored by Yusuke Wada · committed by GitHub · parents b314348, f14ec5d · Browse files · 7 files+403 added−214 removed
This commit

State

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

Diff stats

7 files+403 added−214 removed

  • tests:+230 added−117 removed
  • other:+173 added−97 removed

7 files+403 added−214 removed

modified:src/middleware/cookie/index.test.ts+78 added-47 removed
modified:src/middleware/cookie/index.ts+12 added-5 removed
modified:src/context.ts+25 added-8 removed
5 unmodified lines
6type Data = string | ArrayBuffer | ReadableStream78export type Env = Record<string, any>910export class Context<RequestParamKeyType = string, E = Env> {10export class Context<RequestParamKeyType extends string = string, E = Env> {11 req: Request<RequestParamKeyType>12 res: Response = undefined13 env: E14 event: FetchEvent
18 unmodified lines
33 this._map = {}34 Object.assign(this, opts)35 }3637 private initRequest<T>(req: Request<T>): Request<T> {38 req.header = (name: string): string => {39 return req.headers.get(name)40 }41 req.query = (key: string): string => {37 private initRequest<T extends string>(req: Request<T>): Request<T> {38 req.header = ((name?: string): string | Record<string, string> => {39 if (name) {40 return req.headers.get(name)41 } else {42 const result: Record<string, string> = {}43 for (const [key, value] of req.headers) {44 result[key] = value45 }46 return result47 }48 }) as typeof req.header4950 req.query = ((key?: string): string | Record<string, string> => {51 const url = new URL(req.url)52 if (key) {53 return url.searchParams.get(key)54 } else {55 const result: Record<string, string> = {}56 for (const [key, value] of url.searchParams) {57 result[key] = value58 }43 return url.searchParams.get(key)44 }59 return result60 }61 }) as typeof req.query62 return req63 }6465 header(name: string, value: string): void {
84 unmodified lines
modified:src/hono.test.ts+152 added-70 removed
1import type { Context } from './context'2import type { Next } from './hono'3import { Hono, Route } from './hono'3import { Hono } from './hono'4import { poweredBy } from './middleware/powered-by'56describe('GET Request', () => {7 const app = new Hono()
172 unmodified lines
180 })181})182183describe('param and query', () => {184 const apps: Record<string, Hono> = {}185 apps['get by name'] = (() => {184 const app = new Hono()186 const app = new Hono()187186 app.get('/entry/:id', (c) => {187 const id = c.req.param('id')188 return c.text(`id is ${id}`)189 })188 app.get('/entry/:id', (c) => {189 const id = c.req.param('id')190 return c.text(`id is ${id}`)191 })192191 app.get('/date/:date{[0-9]+}', (c) => {192 const date = c.req.param('date')193 return c.text(`date is ${date}`)194 })193 app.get('/date/:date{[0-9]+}', (c) => {194 const date = c.req.param('date')195 return c.text(`date is ${date}`)196 })197196 app.get('/search', (c) => {197 const name = c.req.query('name')198 return c.text(`name is ${name}`)199 })198 app.get('/search', (c) => {199 const name = c.req.query('name')200 return c.text(`name is ${name}`)201 })202201 app.get('/add-header', (c) => {202 const bar = c.req.header('X-Foo')203 return c.text(`foo is ${bar}`)204 })203 app.get('/add-header', (c) => {204 const bar = c.req.header('X-Foo')205 return c.text(`foo is ${bar}`)206 })207206 it('param of /entry/:id is found', async () => {207 const res = await app.request('http://localhost/entry/123')208 expect(res.status).toBe(200)209 expect(await res.text()).toBe('id is 123')210 })208 return app209 })()210212 it('param of /date/:date is found', async () => {213 const res = await app.request('http://localhost/date/0401')214 expect(res.status).toBe(200)215 expect(await res.text()).toBe('date is 0401')216 })211 apps['get all as an object'] = (() => {212 const app = new Hono()213218 it('query of /search?name=sam is found', async () => {219 const res = await app.request('http://localhost/search?name=sam')220 expect(res.status).toBe(200)221 expect(await res.text()).toBe('name is sam')222 })214 app.get('/entry/:id', (c) => {215 const { id } = c.req.param()216 return c.text(`id is ${id}`)217 })218219 app.get('/date/:date{[0-9]+}', (c) => {220 const { date } = c.req.param()221 return c.text(`date is ${date}`)222 })223224 app.get('/search', (c) => {225 const { name } = c.req.query()226 return c.text(`name is ${name}`)227 })228229 app.get('/add-header', (c) => {230 const { 'x-foo': bar } = c.req.header()231 return c.text(`foo is ${bar}`)232 })233234 return app235 })()236237 describe.each(Object.keys(apps))('%s', (name) => {238 const app = apps[name]239240 it('param of /entry/:id is found', async () => {241 const res = await app.request('http://localhost/entry/123')242 expect(res.status).toBe(200)243 expect(await res.text()).toBe('id is 123')244 })245246 it('param of /date/:date is found', async () => {247 const res = await app.request('http://localhost/date/0401')248 expect(res.status).toBe(200)249 expect(await res.text()).toBe('date is 0401')250 })251252 it('query of /search?name=sam is found', async () => {253 const res = await app.request('http://localhost/search?name=sam')254 expect(res.status).toBe(200)255 expect(await res.text()).toBe('name is sam')256 })257224 it('/add-header header - X-Foo is Bar', async () => {225 const req = new Request('http://localhost/add-header')226 req.headers.append('X-Foo', 'Bar')227 const res = await app.request(req)228 expect(res.status).toBe(200)229 expect(await res.text()).toBe('foo is Bar')258 it('/add-header header - X-Foo is Bar', async () => {259 const req = new Request('http://localhost/add-header')260 req.headers.append('X-Foo', 'Bar')261 const res = await app.request(req)262 expect(res.status).toBe(200)263 expect(await res.text()).toBe('foo is Bar')264 })265 })266})267268describe('Middleware', () => {
302 unmodified lines
571 expect(res.headers.get('X-Header-2')).toBe('bar')572 })573})574540describe('`Route` with app.route', () => {541 const app = new Hono()575describe('Hono with `app.route`', () => {576 describe('Basic', () => {543 const route = new Route()544 route.get('/post', (c) => c.text('GET /POST'))545 route.post('/post', (c) => c.text('POST /POST'))546 app.route('/v1', route)577 const app = new Hono()578 const api = new Hono()579 const middleware = new Hono()580 api.get('/posts', (c) => c.text('List'))581 api.post('/posts', (c) => c.text('Create'))582 api.get('/posts/:id', (c) => c.text(`GET ${c.req.param('id')}`))583 api.use('*', async (c, next) => {584 await next()585 c.res.headers.append('x-custom-a', 'a')586 })587 app.route('/api', api)588589 middleware.use('*', async (c, next) => {590 await next()591 c.res.headers.append('x-custom-b', 'b')592 })593594 app.route('/api', middleware)595548 it('Should return 200 response - GET /v1/post', async () => {549 const res = await app.request('http://localhost/v1/post')596 it('Should return not found response', async () => {597 const res = await app.request('http://localhost/')598 expect(res.status).toBe(404)599 })600601 it('Should return not found response', async () => {602 const res = await app.request('http://localhost/posts')603 expect(res.status).toBe(404)604 })605606 test('GET /api/posts', async () => {607 const res = await app.request('http://localhost/api/posts')608 expect(res.status).toBe(200)551 expect(await res.text()).toBe('GET /POST')609 expect(await res.text()).toBe('List')610 })611554 it('Should return 200 response - POST /v1/post', async () => {555 const res = await app.request('http://localhost/v1/post', { method: 'POST' })612 test('Custom header by middleware', async () => {613 const res = await app.request('http://localhost/api/posts')614 expect(res.status).toBe(200)557 expect(await res.text()).toBe('POST /POST')615 expect(res.headers.get('x-custom-a')).toBe('a')616 expect(res.headers.get('x-custom-b')).toBe('b')617 })618560 it('Should return 404 response - DELETE /v1/post', async () => {561 const res = await app.request('http://localhost/v1/post', { method: 'DELETE' })562 expect(res.status).toBe(404)619 test('POST /api/posts', async () => {620 const res = await app.request('http://localhost/api/posts', { method: 'POST' })621 expect(res.status).toBe(200)622 expect(await res.text()).toBe('Create')623 })624565 it('Should return 404 response - GET /post', async () => {566 const res = await app.request('http://localhost/post')567 expect(res.status).toBe(404)625 test('GET /api/posts/123', async () => {626 const res = await app.request('http://localhost/api/posts/123')627 expect(res.status).toBe(200)628 expect(await res.text()).toBe('GET 123')629 })630 })631632 describe('Chaining', () => {572 const route = new Route()633 const app = new Hono()634 const route = new Hono()635 route.get('/post', (c) => c.text('GET /POST v2')).post((c) => c.text('POST /POST v2'))636 app.route('/v2', route)637638 it('Should return 200 response - GET /v2/post', async () => {
13 unmodified lines
652 expect(res.status).toBe(404)653 })654 })655594 describe('Named parameter', () => {595 const route = new Route()596 route.get('/post/:id', (c) => {597 const id = c.req.param('id')598 return c.text(`GET /post/${id} v3`)656 describe('Nested', () => {657 const app = new Hono()658 const api = new Hono()659 const book = new Hono()660661 book.get('/', (c) => c.text('list books'))662 book.get('/:id', (c) => c.text(`book ${c.req.param('id')}`))663664 api.get('/', (c) => c.text('this is API'))665 api.route('/book', book)666667 app.get('/', (c) => c.text('root'))668 app.route('/v2', api)669670 it('Should return 200 response - GET /', async () => {671 const res = await app.request('http://localhost/')672 expect(res.status).toBe(200)673 expect(await res.text()).toBe('root')674 })600 app.route('/v3', route)675602 it('Should return 200 response - GET /v3/post/1', async () => {603 const res = await app.request('http://localhost/v3/post/1')676 it('Should return 200 response - GET /v2', async () => {677 const res = await app.request('http://localhost/v2')678 expect(res.status).toBe(200)605 expect(await res.text()).toBe('GET /post/1 v3')679 expect(await res.text()).toBe('this is API')680 })681607 it('Should return 404 response - GET /v3/post', async () => {608 const res = await app.request('http://localhost/v3/post/abc/def')609 expect(res.status).toBe(404)682 it('Should return 200 response - GET /v2/book', async () => {683 const res = await app.request('http://localhost/v2/book')684 expect(res.status).toBe(200)685 expect(await res.text()).toBe('list books')686 })687688 it('Should return 200 response - GET /v2/book/123', async () => {689 const res = await app.request('http://localhost/v2/book/123')690 expect(res.status).toBe(200)691 expect(await res.text()).toBe('book 123')692 })693 })694})695696describe('Multiple handler', () => {
80 unmodified lines
modified:src/hono.ts+45 added-64 removed
6 unmodified lines
7import { TrieRouter } from './router/trie-router' // Default Router8import { getPathFromURL, mergePath } from './utils/url'910declare global {11 interface Request<ParamKeyType = string> {12 param: (key: ParamKeyType) => string13 query: (key: string) => string14 header: (name: string) => string11 interface Request<ParamKeyType extends string = string> {12 param: {13 (key: ParamKeyType): string14 (): Record<ParamKeyType, string>15 }16 query: {17 (key: string): string18 (): Record<string, string>19 }20 header: {21 (name: string): string22 (): Record<string, string>23 }24 }25}2618export type Handler<RequestParamKeyType = string, E = Env> = (27export type Handler<RequestParamKeyType extends string = string, E = Env> = (28 c: Context<RequestParamKeyType, E>,29 next: Next30) => Response | Promise<Response> | void | Promise<void>31export type NotFoundHandler<E = Env> = (c: Context<string, E>) => Response
37 unmodified lines
69} {70 return class {} as any71}7264interface Routing<E extends Env> {73interface Route<E extends Env> {74 path: string66 method: Methods75 method: string76 handler: Handler<string, E>77}7870export class Route<E = Env, P extends string = ''> extends defineDynamicClass()<E, P, Route<E, P>> {71 routes: Routing<E>[] = []72 #path: string = ''7374 constructor() {75 super()76 const allMethods = [...methods, METHOD_NAME_ALL_LOWERCASE]7778 allMethods.map((method) => {79 this[method] = <Path extends string>(80 args1: Path | Handler<ParamKeys<Path>, E>,81 ...args: [Handler<ParamKeys<Path>, E>]82 ) => {83 if (typeof args1 === 'string') {84 this.#path = args185 } else {86 this.add(method, this.#path, args1)87 }88 args.map((handler) => {89 if (typeof handler !== 'string') {90 this.add(method, this.#path, handler)91 }92 })93 return this94 }95 })96 }9798 private add(method: Methods, path: string, handler: Handler<string, E>): Route<E, P> {99 const r: Routing<E> = { path: path, method: method, handler: handler }100 this.routes.push(r)101 return this102 }103}104105export class Hono<E = Env, P extends string = ''> extends defineDynamicClass()<E, P, Hono<E, P>> {79export class Hono<E = Env, P extends string = '/'> extends defineDynamicClass()<E, P, Hono<E, P>> {80 readonly routerClass: { new (): Router<any> } = TrieRouter81 readonly strict: boolean = true // strict routing - default is true108 #router: Router<Handler<string, E>>109 #tempPath: string110 private path: string82 private _router: Router<Handler<string, E>>83 private _tempPath: string84 private path: string = '/'8586 routes: Route<E>[] = []8788 constructor(init: Partial<Pick<Hono, 'routerClass' | 'strict'>> = {}) {89 super()9091 const allMethods = [...methods, METHOD_NAME_ALL_LOWERCASE]
17 unmodified lines
109 })110111 Object.assign(this, init)112137 this.#router = new this.routerClass()138 this.#tempPath = null113 this._router = new this.routerClass()114 this._tempPath = null115 }116117 private notFoundHandler: NotFoundHandler = (c: Context) => {118 const message = '404 Not Found'
5 unmodified lines
124 const message = 'Internal Server Error'125 return c.text(message, 500)126 }127152 route(path: string, route?: Route<any>): Hono<E, P> {153 const newHono: Hono<E, P> = new Hono()154 newHono.#tempPath = path155 newHono.#router = this.#router156157 if (route) {158 route.routes.map((r) => {159 newHono.addRoute(r.method, r.path, r.handler)128 route(path: string, app?: Hono<any>): Hono<E, P> {129 this._tempPath = path130 if (app) {131 app.routes.map((r) => {132 this.addRoute(r.method, r.path, r.handler)133 })134 }135163 return newHono136 return this137 }138139 use(path: string, ...middleware: Handler<string, E>[]): Hono<E, P>140 use(...middleware: Handler<string, E>[]): Hono<E, P>
20 unmodified lines
161 }162163 private addRoute(method: string, path: string, handler: Handler<string, E>): void {164 method = method.toUpperCase()192 if (this.#tempPath) {193 path = mergePath(this.#tempPath, path)165 if (this._tempPath) {166 path = mergePath(this._tempPath, path)167 }195 this.#router.add(method, path, handler)168 this._router.add(method, path, handler)169 const r: Route<E> = { path: path, method: method, handler: handler }170 this.routes.push(r)171 }172173 private async matchRoute(method: string, path: string): Promise<Result<Handler<string, E>>> {199 return this.#router.match(method, path)174 return this._router.match(method, path)175 }176177 private async dispatch(request: Request, event?: FetchEvent, env?: E): Promise<Response> {178 const path = getPathFromURL(request.url, { strict: this.strict })179 const method = request.method180181 const result = await this.matchRoute(method, path)207 request.param = (key: string): string => {208 if (result) return result.params[key]209 }182 request.param = ((key?: string): string | Record<string, string> => {183 if (result) {184 if (key) {185 return result.params[key]186 } else {187 return result.params188 }189 }190 }) as typeof request.param191 const handlers = result ? result.handlers : [this.notFoundHandler]192193 const c = new Context<string, E>(request, { env: env, event: event, res: undefined })194 c.notFound = () => this.notFoundHandler(c)
35 unmodified lines
modified:src/index.ts+1 added-1 removed
modified:README.md+90 added-19 removed
50 unmodified lines
5152Routers used in Hono are really smart.5354- **TrieRouter**(default) - Implemented with Trie tree structure.55- **RegExpRouter** - Match routes with one big Regex made before dispatching at once.55- **RegExpRouter** - Match the route with using one big Regex made before dispatch.5657## Hono in 1 minute5859A demonstration to create an application for Cloudflare Workers with Hono.
32 unmodified lines
9293And, the routing of Hono is so flexible. It's easy to construct large web applications.9495```ts96import { Hono, Route } from 'hono'97import { cors } from 'hono/cors'96import { Hono } from 'hono'97import { basicAuth } from 'hono/basic-auth'9899const app = new Hono()100101const v1 = new Route()99const v1 = new Hono()100v1.get('/posts', (c) => {101 return c.text('list pots')102})105 .post('/posts', cors(), (c) => {103 .post(basicAuth({ username, password }), (c) => {104 return c.text('created!', 201)105 })106 .get('/posts/:id', (c) => {107 const id = c.req.param('id')108 return c.text(`your id is ${id}`)109 })110111const app = new Hono()112app.route('/v1', v1)113```114115### Web Standard
22 unmodified lines
138An instance of `Hono` has these methods.139140- app.**HTTP_METHOD**(\[path,\] handler|middleware...)141- app.**all**(\[path,\] handler|middleware...)143- app.**route**(path, \[Route\])142- app.**route**(path, \[app\])143- app.**use**(\[path,\] middleware)144- app.**notFound**(handler)145- app.**onError**(err, handler)146- app.**fire**()
7 unmodified lines
154```ts155// HTTP Methods156app.get('/', (c) => c.text('GET /'))157app.post('/', (c) => c.text('POST /'))158app.put('/', (c) => c.text('PUT /'))159app.delete('/', (c) => c.text('DELETE /'))160161// Wildcard162app.get('/wild/*/card', (c) => {163 return c.text('GET /wild/*/card')
11 unmodified lines
175 ...176})177```178179or all parameters at once:180181```ts182app.get('/posts/:id/comment/:comment_id', (c) => {183 const { id, comment_id } = c.req.param()184 ...185})186```187188### Regexp189190```ts191app.get('/post/:date{[0-9]+}/:title{[a-z]+}', (c) => {182 const date = c.req.param('date')183 const title = c.req.param('title')192 const { date, title } = c.req.param()193 ...194})195```196
30 unmodified lines
227 return c.text(`Status is ${response.status}`)228})229```230222## Route231## Grouping232224`Route` object enables Nested route.233Group the routes with `Hono` instance and add them to the main app with `route` method.234235```ts227const book = new Route()236const book = new Hono()237238book.get('/', (c) => c.text('List Books')) // GET /book239book.get('/:id', (c) => {240 // GET /book/:id
1 unmodified line
242 return c.text('Get Book: ' + id)243})244book.post('/', (c) => c.text('Create Book')) // POST /book245246const app = new Hono()247app.route('/book', book)248```249250## Middleware
96 unmodified lines
347 const query = c.req.query('q')348 ...349})350351// Get all params at once352app.get('/search', (c) => {353 const { q, limit, offset } = c.req.query()354 ...355})356357// Captured params358app.get('/entry/:id', (c) => {359 const id = c.req.param('id')360 ...
81 unmodified lines
442### c.res443444```ts445// Response object430app.use('/', (c, next) => {431 next()446app.use('/', async (c, next) => {447 await next()448 c.res.headers.append('X-Debug', 'Debug message')449})450```451452### c.event453454```ts455// FetchEvent object440app.use('*', async (c, next) => {456app.get('/foo', async (c) => {457 c.event.waitUntil(442 ...458 c.env.KV.put(key, data)459 )444 await next()460 ...461})462```463464### c.env
109 unmodified lines
574```575npx create-cloudflare my-app https://github.com/honojs/hono-minimal576```577562## Examples578## Practical Example579580How about writing web API with Hono?581582```ts583import { Hono } from 'hono'584import { cors } from 'hono/cors'585import { basicAuth } from 'hono/basic-auth'586import { prettyJSON } from 'hono/pretty-json'587import { getPosts, getPosts, createPost } from './model'588589const app = new Hono()590app.get('/', (c) => c.text('Pretty Blog API'))591app.use('*', prettyJSON())592app.notFound((c) => c.json({ message: 'Not Found', ok: false }, 404))593594export interface Bindings {595 USERNAME: string596 PASSWORD: string597}598599const api = new Hono<Bindings>()600601api.get('/posts', (c) => {602 const { limit, offset } = c.req.query()603 const posts = getPosts({ limit, offset })604 return c.json({ posts })605})606607api.get('/posts/:id', (c) => {608 const id = c.req.param('id')609 const post = getPost({ id })610 return c.json({ post })611})612613api.post(614 '/posts',615 async (c, next) => {616 const auth = basicAuth({ username: c.env.USERNAME, password: c.env.PASSWORD })617 await auth(c, next)618 },619 async (c) => {620 const post = await c.req.json<POST>()621 const ok = createPost({ post })622 return c.json({ ok })623 }624)625626app.use('/posts/*', cors())627628app.route('/api', api)629630export default app631```632633## Other Examples634635- Hono Examples - <https://github.com/honojs/examples>636637## Related projects638
31 unmodified lines