Skip to content
Myr

feat: Add new shortcuts for request/response (#62)

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

* Add new shortcuts for request/response * We have only `param`, we can not use `params` * Update readme * tweak

authored by Yusuke Wada · committed by Yusuke Wada · parent ff375c6 · Browse files · 11 files+184 added−67 removed
This commit

State

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

Diff stats

11 files+184 added−67 removed

  • tests:+86 added−22 removed
  • other:+98 added−45 removed

11 files+184 added−67 removed

modified:example/basic/index.js+4 added-4 removed
modified:example/blog/src/controller.ts+3 added-3 removed
modified:example/compute-at-edge/index.js+1 added-1 removed
modified:example/jsx-ssr/src/index.js+1 added-1 removed
46 unmodified lines
47 return c.html(html)48})4950app.get('/post/:id{[0-9]+}', (c) => {51 const id = c.req.params('id')51 const id = c.req.param('id')52 const post = getPost(id)53 if (!post) {54 return c.text('Not Found', 404)55 }
6 unmodified lines
modified:src/middleware/logger/logger.test.ts+2 added-2 removed
16 unmodified lines
17 app.get('/long', () => new Response(longRandomString))18 app.get('/empty', () => new Response(''))1920 it('Log status 200 with empty body', async () => {21 const req = new Request('http://localhost/short')21 const req = new Request('http://localhost/empty')22 const res = await app.dispatch(req)23 expect(res).not.toBeNull()24 expect(res.status).toBe(200)25 expect(log.startsWith(' --> GET /empty \x1b[32m200\x1b[0m')).toBe(true)
17 unmodified lines
43 expect(log.startsWith(' --> GET /long \x1b[32m200\x1b[0m')).toBe(true)44 expect(log.endsWith(` ${longRandomString.length / 1024}kB`)).toBe(true)45 })4647 it.only('Log status 404', async () => {47 it('Log status 404', async () => {48 const msg = 'Default 404 Nout Found'49 app.notFound = () => {50 return new Response(msg, { status: 404 })51 }
9 unmodified lines
modified:src/middleware/default.ts+3 added
4 unmodified lines
5 // eslint-disable-next-line6 const url = new URL(c.req.url)7 return url.searchParams.get(key)8 }9 c.req.header = (name: string): string => {10 return c.req.headers.get(name)11 }1213 await next()1415 if (c.res.body) {
11 unmodified lines
modified:src/context.ts+22 added-1 removed
7 unmodified lines
8 req: Request9 res: Response10 env: Env11 event: FetchEvent12 private _headers: Headers13 private _status: number14 private _statusText: string15 body: (body: BodyInit, init?: ResponseInit) => Response1617 constructor(req: Request, opts?: { res: Response; env: Env; event: FetchEvent }) {18 this.req = req19 if (opts) {20 this.res = opts.res21 this.env = opts.env22 this.event = opts.event23 }24 this._headers = {}25 this.body = this.newResponse26 }2722 newResponse(body?: BodyInit | null | undefined, init?: ResponseInit | undefined): Response {28 header(name: string, value: string): void {29 this._headers[name] = value30 }3132 status(number: number): void {33 this._status = number34 }3536 statusText(text: string): void {37 this._statusText = text38 }3940 newResponse(body: BodyInit, init: ResponseInit = {}): Response {41 init.status = this._status || init.status42 init.statusText = this._statusText || init.statusText43 init.headers = { ...init.headers, ...this._headers }44 return new Response(body, init)45 }4647 text(text: string, status: number = 200, headers: Headers = {}): Response {
56 unmodified lines
modified:src/hono.ts+3 added-2 removed
8 unmodified lines
9const METHOD_NAME_OF_ALL = 'ALL'1011declare global {12 interface Request {13 params: (key: string) => string13 param: (key: string) => string14 query: (key: string) => string | null15 header: (name: string) => string16 parsedBody: any17 }18}19
106 unmodified lines
126 const [method, path] = [request.method, getPathFromURL(request.url)]127128 const result = await this.matchRoute(method, path)129129 request.params = (key: string): string => {130 request.param = (key: string): string => {131 if (result) {132 return result.params[key]133 }134 return ''
55 unmodified lines
modified:test/context.test.ts+30 added-4 removed
2 unmodified lines
3describe('Context', () => {4 const req = new Request('http://localhost/')5 const c = new Context(req)67 it('c.text', async () => {7 it('c.text()', async () => {8 const res = c.text('text in c', 201, { 'X-Custom': 'Message' })9 expect(res.status).toBe(201)10 expect(res.headers.get('Content-Type')).toBe('text/plain')11 expect(await res.text()).toBe('text in c')12 expect(res.headers.get('X-Custom')).toBe('Message')13 })1415 it('c.json', async () => {15 it('c.json()', async () => {16 const res = c.json({ message: 'Hello' }, 201, { 'X-Custom': 'Message' })17 expect(res.status).toBe(201)18 expect(res.headers.get('Content-Type')).toMatch('application/json')19 const text = await res.text()
1 unmodified line
21 expect(object.message).toBe('Hello')22 expect(res.headers.get('X-Custom')).toBe('Message')23 })2425 it('c.html', async () => {25 it('c.html()', async () => {26 const res = c.html('<h1>Hello! Hono!</h1>', 201, { 'X-Custom': 'Message' })27 expect(res.status).toBe(201)28 expect(res.headers.get('Content-Type')).toMatch('text/html')29 expect(await res.text()).toBe('<h1>Hello! Hono!</h1>')30 expect(res.headers.get('X-Custom')).toBe('Message')31 })3233 it('c.redirect', async () => {33 it('c.redirect()', async () => {34 let res = c.redirect('/destination')35 expect(res.status).toBe(302)36 expect(res.headers.get('Location')).toMatch(/^https?:\/\/.+\/destination$/)37 res = c.redirect('https://example.com/destination')38 expect(res.status).toBe(302)39 expect(res.headers.get('Location')).toBe('https://example.com/destination')40 })4142 it('c.header()', async () => {43 c.header('X-Foo', 'Bar')44 const res = c.body('Hi')45 const foo = res.headers.get('X-Foo')46 expect(foo).toBe('Bar')47 })4849 it('c.status() and c.statusText()', async () => {50 c.status(201)51 c.statusText('Created!!!!')52 const res = c.body('Hi')53 expect(res.status).toBe(201)54 expect(res.statusText).toBe('Created!!!!')55 })5657 it('Complext pattern', async () => {58 c.status(404)59 c.statusText('Hono is Not Found')60 const res = c.json({ hono: 'great app' })61 expect(res.status).toBe(404)62 expect(res.statusText).toBe('Hono is Not Found')63 expect(res.headers.get('Content-Type')).toMatch(/json/)64 const obj: { [key: string]: string } = await res.json()65 expect(obj['hono']).toBe('great app')66 })67})
modified:test/hono.test.ts+54 added-16 removed
1import { Hono } from '../src/hono'23describe('GET Request', () => {4 const app = new Hono()56 app.get('/hello', () => {7 return new Response('hello', {8 status: 200,9 })10 })1112 app.get('/hello-with-shortcuts', (c) => {13 c.header('X-Custom', 'This is Hono')14 c.statusText('Hono is created')15 c.status(201)16 return c.html('<h1>Hono!!!</h1>')17 })1819 app.notFound = () => {20 return new Response('not found', {21 status: 404,22 })23 }2425 it('GET /hello is ok', async () => {26 const req = new Request('http://localhost/hello')27 const res = await app.dispatch(req)28 expect(res).not.toBeNull()29 expect(res.status).toBe(200)30 expect(await res.text()).toBe('hello')31 })3233 it('GET /hell-with-shortcuts is ok', async () => {34 const req = new Request('http://localhost/hello-with-shortcuts')35 const res = await app.dispatch(req)36 expect(res).not.toBeNull()37 expect(res.status).toBe(201)38 expect(res.statusText).toBe('Hono is created')39 expect(res.headers.get('X-Custom')).toBe('This is Hono')40 expect(res.headers.get('Content-Type')).toMatch(/text\/html/)41 expect(await res.text()).toBe('<h1>Hono!!!</h1>')42 })4344 it('GET / is not found', async () => {45 const req = new Request('http://localhost/')46 const res = await app.dispatch(req)47 expect(res).not.toBeNull()
57 unmodified lines
105 expect(res.status).toBe(404)106 })107})10887describe('params and query', () => {109describe('param and query', () => {110 const app = new Hono()11190 app.get('/entry/:id', async (c) => {91 const id = await c.req.params('id')112 app.get('/entry/:id', (c) => {113 const id = c.req.param('id')114 return new Response(`id is ${id}`, {115 status: 200,116 })117 })11897 app.get('/search', async (c) => {98 const name = await c.req.query('name')119 app.get('/search', (c) => {120 const name = c.req.query('name')121 return new Response(`name is ${name}`, {122 status: 200,123 })124 })125126 app.get('/add-header', (c) => {127 const bar = c.req.header('X-Foo')128 return new Response(`foo is ${bar}`, {129 status: 200,130 })131 })132104 it('params of /entry/:id is found', async () => {133 it('param of /entry/:id is found', async () => {134 const req = new Request('http://localhost/entry/123')135 const res = await app.dispatch(req)136 expect(res.status).toBe(200)137 expect(await res.text()).toBe('id is 123')138 })139140 it('query of /search?name=sam is found', async () => {141 const req = new Request('http://localhost/search?name=sam')142 const res = await app.dispatch(req)143 expect(res.status).toBe(200)144 expect(await res.text()).toBe('name is sam')145 })146147 it('/add-header header - X-Foo is Bar', async () => {148 const req = new Request('http://localhost/add-header')149 req.headers.append('X-Foo', 'Bar')150 const res = await app.dispatch(req)151 expect(res.status).toBe(200)152 expect(await res.text()).toBe('foo is Bar')153 })154})155156describe('Middleware', () => {157 const app = new Hono()
6 unmodified lines
164165 // Apeend Custom Header166 app.use('*', async (c, next) => {167 await next()130 await c.res.headers.append('x-custom', 'root')168 c.res.headers.append('x-custom', 'root')169 })170171 app.use('/hello', async (c, next) => {172 await next()135 await c.res.headers.append('x-message', 'custom-header')173 c.res.headers.append('x-message', 'custom-header')174 })175176 app.use('/hello/*', async (c, next) => {177 await next()140 await c.res.headers.append('x-message-2', 'custom-header-2')178 c.res.headers.append('x-message-2', 'custom-header-2')179 })180181 app.get('/hello', () => {182 return new Response('hello')183 })184 app.get('/hello/:message', (c) => {147 const message = c.req.params('message')185 const message = c.req.param('message')186 return new Response(`${message}`)187 })188189 it('logging and custom header', async () => {190 const req = new Request('http://localhost/hello')191 const res = await app.dispatch(req)192 expect(res.status).toBe(200)193 expect(await res.text()).toBe('hello')156 expect(await res.headers.get('x-custom')).toBe('root')157 expect(await res.headers.get('x-message')).toBe('custom-header')158 expect(await res.headers.get('x-message-2')).toBe('custom-header-2')194 expect(res.headers.get('x-custom')).toBe('root')195 expect(res.headers.get('x-message')).toBe('custom-header')196 expect(res.headers.get('x-message-2')).toBe('custom-header-2')197 })198161 it('logging and custom header with named params', async () => {199 it('logging and custom header with named param', async () => {200 const req = new Request('http://localhost/hello/message')201 const res = await app.dispatch(req)202 expect(res.status).toBe(200)203 expect(await res.text()).toBe('message')166 expect(await res.headers.get('x-custom')).toBe('root')167 expect(await res.headers.get('x-message-2')).toBe('custom-header-2')204 expect(res.headers.get('x-custom')).toBe('root')205 expect(res.headers.get('x-message-2')).toBe('custom-header-2')206 })207})208209describe('Custom 404', () => {
66 unmodified lines
modified:README.md+61 added-33 removed
33 unmodified lines
34## Hono in 1 minute3536Below is a demonstration to create an application of Cloudflare Workers with Hono.3738![Demo](https://user-images.githubusercontent.com/10682/148223268-2484a891-57c1-472f-9df3-936a5586f002.gif)38![Demo](https://user-images.githubusercontent.com/10682/151102477-be0f950e-8d23-49c5-b6d8-d8ecb6b7484e.gif)3940## Install4142You can install from npm registry:
46 unmodified lines
89### Named Parameter9091```js92app.get('/user/:name', (c) => {93 const name = c.req.params('name')93 const name = c.req.param('name')94 ...95})96```9798### Regexp99100```js101app.get('/post/:date{[0-9]+}/:title{[a-z]+}', (c) => {102 const date = c.req.params('date')103 const title = c.req.params('title')102 const date = c.req.param('date')103 const title = c.req.param('title')104 ...105```106107### Chained Route
110 unmodified lines
218219### c.req220221```js222222// Get Request object223app.get('/hello', (c) => {224 const userAgent = c.req.headers.get('User-Agent')225 ...226})227228// Shortcut to get a header value229app.get('/shortcut', (c) => {230 const userAgent = c.req.header('User-Agent')231 ...232})233234// Query params235app.get('/search', (c) => {236 const query = c.req.query('q')237 ...238})239240// Captured params241app.get('/entry/:id', (c) => {237 const id = c.req.params('id')242 const id = c.req.param('id')243 ...244})245```246242### c.res247### Shortcuts for Response248249```js245// Response object246app.use('/', (c, next) => {247 next()248 c.res.headers.append('X-Debug', 'Debug message')250app.get('/welcome', (c) => {251 c.header('X-Message', 'Hello!')252 c.header('Content-Type', 'text/plain')253 c.status(201)254 c.statusText('201 Content Created')255 return c.body('Thank you for comming')256 /*257 Same as:258 return new Response('Thank you for comming', {259 status: 201,260 statusText: '201 Content Created',261 headers: {262 'X-Message': 'Hello',263 'Content-Type': 'text/plain'264 }265 })266 */267})268```269252### c.event253254```js255// FetchEvent object256app.use('*', async (c, next) => {257 c.event.waitUntil(258 ...259 )260 await next()261})262```263264### c.env265266```js267// Environment object for Cloudflare Workers268app.get('*', async c => {269 const counter = c.env.COUNTER270 ...271})272```273270### c.text()271272Render text as `Content-Type:text/plain`:273
31 unmodified lines
305app.get('/redirect', (c) => c.redirect('/'))306app.get('/redirect-permanently', (c) => c.redirect('/', 301))307```308309### c.res310311```js312// Response object313app.use('/', (c, next) => {314 next()315 c.res.headers.append('X-Debug', 'Debug message')316})317```318319### c.event320321```js322// FetchEvent object323app.use('*', async (c, next) => {324 c.event.waitUntil(325 ...326 )327 await next()328})329```330331### c.env332333```js334// Environment object for Cloudflare Workers335app.get('*', async c => {336 const counter = c.env.COUNTER337 ...338})339```340341## fire342343`app.fire()` do:344
117 unmodified lines