Skip to content
Myr

feat: add `request` method (#132)

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

Add `request` method. It's useful for testing.

authored by Yusuke Wada · committed by GitHub · parent e36b054 · Browse files · 6 files+76 added−72 removed
This commit

State

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

Diff stats

6 files+76 added−72 removed

  • tests:+41 added−66 removed
  • other:+35 added−6 removed

6 files+76 added−72 removed

modified:docs/README.ja.md+12 added
79 unmodified lines
80- app.**notFound**(handler)81- app.**onError**(err, handler)82- app.**fire**()83- app.**fetch**(request, env, event)84- app.**request**(path, option)8586## ルーティング8788### 基本
298 unmodified lines
387export default app388*/389```390391## request392393`request`はテストの時に役に立つメソッドです。394395```js396test('GET /hello is ok', async () => {397 const res = await app.request('http://localhost/hello')398 expect(res.status).toBe(200)399})400```401402## HonoでCloudflare Workersのアプリを作る403404[Wrangler](https://developers.cloudflare.com/workers/cli-wrangler/)もしくは[Miniflare](https://miniflare.dev)を使えば、ローカル環境での開発から、デプロイ・公開までが数行のコマンドで簡単にできます。405
125 unmodified lines
modified:src/context.test.ts+6 added
modified:src/context.ts+2 added-2 removed
53 unmodified lines
54 this._statusText = getStatusText(number)55 }5657 newResponse(data: Data, init: ResponseInit = {}): Response {58 init.status = init.status || this._status59 init.statusText = init.statusText || this._statusText58 init.status = init.status || this._status || 20059 init.statusText = init.statusText || this._statusText || getStatusText(init.status)6061 init.headers = { ...this._headers, ...init.headers }6263 // Content-Length
63 unmodified lines
modified:src/hono.test.ts+35 added-66 removed
15 unmodified lines
16 return c.html('<h1>Hono!!!</h1>')17 })1819 it('GET /hello is ok', async () => {20 const req = new Request('http://localhost/hello')21 const res = await app.dispatch(req)20 const res = await app.request('http://localhost/hello')21 expect(res).not.toBeNull()22 expect(res.status).toBe(200)23 expect(res.statusText).toBe('Hono is OK')24 expect(await res.text()).toBe('hello')25 })2627 it('GET /hell-with-shortcuts is ok', async () => {29 const req = new Request('http://localhost/hello-with-shortcuts')30 const res = await app.dispatch(req)28 const res = await app.request('http://localhost/hello-with-shortcuts')29 expect(res).not.toBeNull()30 expect(res.status).toBe(201)31 expect(res.statusText).toBe('Created')32 expect(res.headers.get('X-Custom')).toBe('This is Hono')
1 unmodified line
34 expect(await res.text()).toBe('<h1>Hono!!!</h1>')35 })3637 it('GET / is not found', async () => {40 const req = new Request('http://localhost/')41 const res = await app.dispatch(req)38 const res = await app.request('http://localhost/')39 expect(res).not.toBeNull()40 expect(res.status).toBe(404)41 expect(res.statusText).toBe('Not Found')42 })43})4445describe('strict parameter', () => {
4 unmodified lines
50 return c.text('/hello')51 })5253 it('/hello/ is not found', async () => {56 let req = new Request('http://localhost/hello')57 let res = await app.dispatch(req)54 let res = await app.request('http://localhost/hello')55 expect(res).not.toBeNull()56 expect(res.status).toBe(200)60 req = new Request('http://localhost/hello/')61 res = await app.dispatch(req)57 res = await app.request('http://localhost/hello/')58 expect(res).not.toBeNull()59 expect(res.status).toBe(404)60 })61 })
5 unmodified lines
67 return c.text('/hello/')68 })6970 it('/hello is not found', async () => {75 let req = new Request('http://localhost/hello/')76 let res = await app.dispatch(req)71 let res = await app.request('http://localhost/hello/')72 expect(res).not.toBeNull()73 expect(res.status).toBe(200)79 req = new Request('http://localhost/hello')80 res = await app.dispatch(req)74 res = await app.request('http://localhost/hello')75 expect(res).not.toBeNull()76 expect(res.status).toBe(404)77 })78 })
5 unmodified lines
84 return c.text('/hello')85 })8687 it('/hello and /hello/ are treated as the same', async () => {94 let req = new Request('http://localhost/hello')95 let res = await app.dispatch(req)88 let res = await app.request('http://localhost/hello')89 expect(res).not.toBeNull()90 expect(res.status).toBe(200)98 req = new Request('http://localhost/hello/')99 res = await app.dispatch(req)91 res = await app.request('http://localhost/hello/')92 expect(res).not.toBeNull()93 expect(res.status).toBe(200)94 })95 })
5 unmodified lines
101 it('Return it self', async () => {102 const appRes = app.get('/', () => new Response('get /'))103 expect(appRes).not.toBeUndefined()104 appRes.delete('/', () => new Response('delete /'))113 const req = new Request('http://localhost/', { method: 'DELETE' })114 const res = await appRes.dispatch(req)105 const res = await appRes.request('http://localhost/', { method: 'DELETE' })106 expect(res).not.toBeNull()107 expect(res.status).toBe(200)108 expect(await res.text()).toBe('delete /')109 })
9 unmodified lines
119 const user = app.route('/user')120 user.get('/login', (c) => c.text('get /user/login'))121 user.post('/regist', (c) => c.text('post /user/regist'))122132 let req = new Request('http://localhost/book', { method: 'GET' })133 let res = await app.dispatch(req)123 let res = await app.request('http://localhost/book', { method: 'GET' })124 expect(res.status).toBe(200)125 expect(await res.text()).toBe('get /book')126137 req = new Request('http://localhost/book/123', { method: 'GET' })138 res = await app.dispatch(req)127 res = await app.request('http://localhost/book/123', { method: 'GET' })128 expect(res.status).toBe(200)129 expect(await res.text()).toBe('get /book/123')130142 req = new Request('http://localhost/book', { method: 'POST' })143 res = await app.dispatch(req)131 res = await app.request('http://localhost/book', { method: 'POST' })132 expect(res.status).toBe(200)133 expect(await res.text()).toBe('post /book')134147 req = new Request('http://localhost/book/', { method: 'GET' })148 res = await app.dispatch(req)135 res = await app.request('http://localhost/book/', { method: 'GET' })136 expect(res.status).toBe(404)137151 req = new Request('http://localhost/user/login', { method: 'GET' })152 res = await app.dispatch(req)138 res = await app.request('http://localhost/user/login', { method: 'GET' })139 expect(res.status).toBe(200)140 expect(await res.text()).toBe('get /user/login')141156 req = new Request('http://localhost/user/regist', { method: 'POST' })157 res = await app.dispatch(req)142 res = await app.request('http://localhost/user/regist', { method: 'POST' })143 expect(res.status).toBe(200)144 expect(await res.text()).toBe('post /user/regist')145 })146})
2 unmodified lines
149 const app = new Hono()150151 app.get('/entry/:id', (c) => {152 const id = c.req.param('id')168 return new Response(`id is ${id}`, {169 status: 200,170 })153 return c.text(`id is ${id}`)154 })155156 app.get('/search', (c) => {157 const name = c.req.query('name')175 return new Response(`name is ${name}`, {176 status: 200,177 })158 return c.text(`name is ${name}`)159 })160161 app.get('/add-header', (c) => {162 const bar = c.req.header('X-Foo')182 return new Response(`foo is ${bar}`, {183 status: 200,184 })163 return c.text(`foo is ${bar}`)164 })165166 it('param of /entry/:id is found', async () => {188 const req = new Request('http://localhost/entry/123')189 const res = await app.dispatch(req)167 const res = await app.request('http://localhost/entry/123')168 expect(res.status).toBe(200)169 expect(await res.text()).toBe('id is 123')170 })171172 it('query of /search?name=sam is found', async () => {195 const req = new Request('http://localhost/search?name=sam')196 const res = await app.dispatch(req)173 const res = await app.request('http://localhost/search?name=sam')174 expect(res.status).toBe(200)175 expect(await res.text()).toBe('name is sam')176 })177178 it('/add-header header - X-Foo is Bar', async () => {179 const req = new Request('http://localhost/add-header')180 req.headers.append('X-Foo', 'Bar')204 const res = await app.dispatch(req)181 const res = await app.request(req)182 expect(res.status).toBe(200)183 expect(await res.text()).toBe('foo is Bar')184 })185})
22 unmodified lines
208 await next()209 c.res.headers.append('x-message-2', 'custom-header-2')210 })211235 app.get('/hello', () => {236 return new Response('hello')212 app.get('/hello', (c) => {213 return c.text('hello')214 })215 app.get('/hello/:message', (c) => {216 const message = c.req.param('message')240 return new Response(`${message}`)217 return c.text(`${message}`)218 })219220 it('logging and custom header', async () => {244 const req = new Request('http://localhost/hello')245 const res = await app.dispatch(req)221 const res = await app.request('http://localhost/hello')222 expect(res.status).toBe(200)223 expect(await res.text()).toBe('hello')224 expect(res.headers.get('x-custom')).toBe('root')225 expect(res.headers.get('x-message')).toBe('custom-header')226 expect(res.headers.get('x-message-2')).toBe('custom-header-2')227 })228229 it('logging and custom header with named param', async () => {254 const req = new Request('http://localhost/hello/message')255 const res = await app.dispatch(req)230 const res = await app.request('http://localhost/hello/message')231 expect(res.status).toBe(200)232 expect(await res.text()).toBe('message')233 expect(res.headers.get('x-custom')).toBe('root')234 expect(res.headers.get('x-message-2')).toBe('custom-header-2')
15 unmodified lines
250 return c.notFound()251 })252253 it('Custom 404 Not Found', async () => {279 let req = new Request('http://localhost/hello')280 let res = await app.dispatch(req)254 let res = await app.request('http://localhost/hello')255 expect(res.status).toBe(200)282 req = new Request('http://localhost/notfound')283 res = await app.dispatch(req)256 res = await app.request('http://localhost/notfound')257 expect(res.status).toBe(404)285 req = new Request('http://localhost/foo')286 res = await app.dispatch(req)258 res = await app.request('http://localhost/foo')259 expect(res.status).toBe(404)260 expect(await res.text()).toBe('Custom 404 Not Found')261 })262})
4 unmodified lines
267 return c.redirect('/')268 })269270 it('Absolute URL', async () => {299 const req = new Request('https://example.com/redirect')300 const res = await app.dispatch(req)271 const res = await app.request('https://example.com/redirect')272 expect(res.status).toBe(302)273 expect(res.headers.get('Location')).toBe('https://example.com/')274 })275})
14 unmodified lines
290 return c.text('Custom Error Message', 500)291 })292293 it('Custom Error Message', async () => {323 let req = new Request('https://example.com/error')324 let res = await app.dispatch(req)294 let res = await app.request('https://example.com/error')295 expect(res.status).toBe(500)296 expect(await res.text()).toBe('Custom Error Message')297 expect(res.headers.get('x-debug')).toBe('This is Error')298329 req = new Request('https://example.com/error-middleware')330 res = await app.dispatch(req)299 res = await app.request('https://example.com/error-middleware')300 expect(res.status).toBe(500)301 expect(await res.text()).toBe('Custom Error Message')302 expect(res.headers.get('x-debug')).toBe('This is Middleware Error')303 })
26 unmodified lines
330 const url = new URL('http://localhost/bar')331 url.searchParams.append('foo', 'bar')332 const req = new Request(url.toString())333 req.headers.append('User-Agent', 'bar')365 const res = await app.dispatch(req)334 const res = await app.request(req)335336 expect(res.status).toBe(200)337 expect(res.headers.get('X-Query')).toBe('bar')338 expect(res.headers.get('X-Param')).toBe('bar')
7 unmodified lines
modified:src/hono.ts+9 added-4 removed
50 unmodified lines
51 this.middlewareRouters = []52 this.tempPath = null53 }5455 notFoundHandler: NotFoundHandler = (c: Context) => {55 private notFoundHandler: NotFoundHandler = (c: Context) => {56 const message = '404 Not Found'57 return c.text(message, 404)58 }5960 errorHandler: ErrorHandler = (err: Error, c: Context) => {60 private errorHandler: ErrorHandler = (err: Error, c: Context) => {61 console.error(`${err.message}`)62 const message = 'Internal Server Error'63 return c.text(message, 500)64 }
66 unmodified lines
131 return this132 }133134 // addRoute('get', '/', handler)135 addRoute(method: string, path: string, handler: Handler): Hono {135 private addRoute(method: string, path: string, handler: Handler): Hono {136 method = method.toUpperCase()137 if (this.tempPath) {138 path = mergePath(this.tempPath, path)139 }140 this.router.add(method, path, handler)141 return this142 }143144 async matchRoute(method: string, path: string): Promise<Result<Handler>> {144 private async matchRoute(method: string, path: string): Promise<Result<Handler>> {145 return this.router.match(method, path)146 }147148 async dispatch(request: Request, env?: Env, event?: FetchEvent): Promise<Response> {
54 unmodified lines
203 async fetch(request: Request, env?: Env, event?: FetchEvent): Promise<Response> {204 return this.dispatch(request, env, event)205 }206207 request(input: RequestInfo, requestInit?: RequestInit) {208 const req = new Request(input, requestInit)209 return this.dispatch(req)210 }211212 fire() {213 addEventListener('fetch', (event: FetchEvent): void => {214 event.respondWith(this.handleEvent(event))215 })
2 unmodified lines
modified:README.md+12 added
79 unmodified lines
80- app.**notFound**(handler)81- app.**onError**(err, handler)82- app.**fire**()83- app.**fetch**(request, env, event)84- app.**request**(path, option)8586## Routing8788### Basic
298 unmodified lines
387export default app388*/389```390391## request392393`request` is a useful method for testing.394395```js396test('GET /hello is ok', async () => {397 const res = await app.request('http://localhost/hello')398 expect(res.status).toBe(200)399})400```401402## Cloudflare Workers with Hono403404Using [Wrangler](https://developers.cloudflare.com/workers/cli-wrangler/) or [Miniflare](https://miniflare.dev), you can develop the application locally and publish it with few commands.405
122 unmodified lines