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
Provenance
- Commit
68444b6- Tree
58e599a- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
Yusuke Wada <yusuke@kamawada.com>- Parent
ff375c6
11 files changed+184 added−67 removed
modified:example/basic/index.js+4 added-4 removed
53 unmodified lines545556575858596061627 unmodified lines7071727374747576777810 unmodified lines8990919293949394959697986 unmodified lines53 unmodified linesapp.get('/hello', () => new Response('This is /hello'))
// Named parameterapp.get('/entry/:id', (c) => { const id = c.req.params('id') const id = c.req.param('id') return c.text(`Your ID is ${id}`)})// Redirectapp.get('/redirect', (c) => c.redirect('/'))7 unmodified lines})
// Request headersapp.get('/user-agent', (c) => { const userAgent = c.req.headers.get('User-Agent') const userAgent = c.req.header('User-Agent') return c.text(`Your UserAgent is ${userAgent}`)})
// JSON10 unmodified linesapp.post('/api/posts', (c) => c.json({ message: 'Created!' }, 201))// default routeapp.get('/api/*', (c) => c.text('API endpoint is not found', 404))
app.post('/form', async (ctx) => { return ctx.json(ctx.req.parsedBody || {})app.post('/form', async (c) => { return c.json(c.req.parsedBody || {}) //return new Response('ok /form')})
// Throw Error6 unmodified linesmodified:example/blog/src/controller.ts+3 added-3 removed
22 unmodified lines23242526272728293031323334353636373839402 unmodified lines434445464747484950513 unmodified lines22 unmodified lines return c.json({ post: newPost, ok: true }, 201)}
export const show: Handler = async (c) => { const id = c.req.params('id') const id = c.req.param('id') const post = await Model.getPost(id) if (!post) { return c.json({ error: 'Not Found', ok: false }, 404) } return c.json({ post: post, ok: true })}
export const update: Handler = async (c) => { const id = c.req.params('id') const id = c.req.param('id') if (!(await Model.getPost(id))) { // 204 No Content return c.json({ ok: false }, 204) }2 unmodified lines return c.json({ ok: success })}
export const destroy: Handler = async (c) => { const id = c.req.params('id') const id = c.req.param('id') if (!(await Model.getPost(id))) { // 204 No Content return c.json({ ok: false }, 204) }3 unmodified linesmodified:example/compute-at-edge/index.js+1 added-1 removed
8 unmodified lines910111213131415168 unmodified lines
app.get('/', (c) => c.text('Hono!! Compute@Edge!!'))
app.get('/hello/:name', (c) => { return c.text(`Hello ${c.req.params('name')}!!!!!`) return c.text(`Hello ${c.req.param('name')}!!!!!`)})
app.fire()modified:example/jsx-ssr/src/index.js+1 added-1 removed
46 unmodified lines47 return c.html(html)48 })49 50 app.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 linesmodified:src/middleware/logger/logger.test.ts+2 added-2 removed
16 unmodified lines17 app.get('/long', () => new Response(longRandomString))18 app.get('/empty', () => new Response(''))19 20 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 lines43 expect(log.startsWith(' --> GET /long \x1b[32m200\x1b[0m')).toBe(true)44 expect(log.endsWith(` ${longRandomString.length / 1024}kB`)).toBe(true)45 })46 47- 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 linesmodified:src/middleware/default.ts+3 added
4 unmodified lines5 // 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+ }12 13 await next()14 15 if (c.res.body) {11 unmodified linesmodified:src/context.ts+22 added-1 removed
7 unmodified lines8 req: Request9 res: Response10 env: Env11 event: FetchEvent12+ private _headers: Headers13+ private _status: number14+ private _statusText: string15+ body: (body: BodyInit, init?: ResponseInit) => Response16 17 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 }27 22- newResponse(body?: BodyInit | null | undefined, init?: ResponseInit | undefined): Response {28+ header(name: string, value: string): void {29+ this._headers[name] = value30+ }31+32+ status(number: number): void {33+ this._status = number34+ }35+36+ statusText(text: string): void {37+ this._statusText = text38+ }39+40+ 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 }46 47 text(text: string, status: number = 200, headers: Headers = {}): Response {56 unmodified linesmodified:src/hono.ts+3 added-2 removed
8 unmodified lines9 const METHOD_NAME_OF_ALL = 'ALL'10 11 declare 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 lines126 const [method, path] = [request.method, getPathFromURL(request.url)]127 128 const result = await this.matchRoute(method, path)129 129- request.params = (key: string): string => {130+ request.param = (key: string): string => {131 if (result) {132 return result.params[key]133 }134 return ''55 unmodified linesmodified:test/context.test.ts+30 added-4 removed
2 unmodified lines3 describe('Context', () => {4 const req = new Request('http://localhost/')5 const c = new Context(req)6 7- 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 })14 15- 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 line21 expect(object.message).toBe('Hello')22 expect(res.headers.get('X-Custom')).toBe('Message')23 })24 25- 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 })32 33- 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 })41+42+ 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+ })48+49+ 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+ })56+57+ 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
1 import { Hono } from '../src/hono'2 3 describe('GET Request', () => {4 const app = new Hono()5+6 app.get('/hello', () => {7 return new Response('hello', {8 status: 200,9 })10 })11+12+ 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+ })18+19 app.notFound = () => {20 return new Response('not found', {21 status: 404,22 })23 }24+25 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 })32+33+ 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+ })43+44 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 lines105 expect(res.status).toBe(404)106 })107 })108 87-describe('params and query', () => {109+describe('param and query', () => {110 const app = new Hono()111 90- 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 })118 97- 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 })125 126+ 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+ })132+104- 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 })139+140 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 })146+147+ 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 })155 156 describe('Middleware', () => {157 const app = new Hono()6 unmodified lines164 165 // 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 })170 171 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 })175 176 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 })180 181 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 })188 189 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 })198 161- 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 })208 209 describe('Custom 404', () => {66 unmodified linesmodified:README.md+61 added-33 removed
33 unmodified lines34 ## Hono in 1 minute35 36 Below is a demonstration to create an application of Cloudflare Workers with Hono.37 38-38+39 40 ## Install41 42 You can install from npm registry:46 unmodified lines89 ### Named Parameter90 91 ```js92 app.get('/user/:name', (c) => {93- const name = c.req.params('name')93+ const name = c.req.param('name')94 ...95 })96 ```97 98 ### Regexp99 100 ```js101 app.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 ```106 107 ### Chained Route110 unmodified lines218 219 ### c.req220 221 ```js222-222 // Get Request object223 app.get('/hello', (c) => {224 const userAgent = c.req.headers.get('User-Agent')225 ...226 })227 228+// Shortcut to get a header value229+app.get('/shortcut', (c) => {230+ const userAgent = c.req.header('User-Agent')231+ ...232+})233+234 // Query params235 app.get('/search', (c) => {236 const query = c.req.query('q')237 ...238 })239 240 // Captured params241 app.get('/entry/:id', (c) => {237- const id = c.req.params('id')242+ const id = c.req.param('id')243 ...244 })245 ```246 242-### c.res247+### Shortcuts for Response248 249 ```js245-// Response object246-app.use('/', (c, next) => {247- next()248- c.res.headers.append('X-Debug', 'Debug message')250+app.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 ```269 252-### c.event253-254-```js255-// FetchEvent object256-app.use('*', async (c, next) => {257- c.event.waitUntil(258- ...259- )260- await next()261-})262-```263-264-### c.env265-266-```js267-// Environment object for Cloudflare Workers268-app.get('*', async c => {269- const counter = c.env.COUNTER270- ...271-})272-```273-270 ### c.text()271 272 Render text as `Content-Type:text/plain`:273 31 unmodified lines305 app.get('/redirect', (c) => c.redirect('/'))306 app.get('/redirect-permanently', (c) => c.redirect('/', 301))307 ```308 309+### c.res310+311+```js312+// Response object313+app.use('/', (c, next) => {314+ next()315+ c.res.headers.append('X-Debug', 'Debug message')316+})317+```318+319+### c.event320+321+```js322+// FetchEvent object323+app.use('*', async (c, next) => {324+ c.event.waitUntil(325+ ...326+ )327+ await next()328+})329+```330+331+### c.env332+333+```js334+// Environment object for Cloudflare Workers335+app.get('*', async c => {336+ const counter = c.env.COUNTER337+ ...338+})339+```340+341 ## fire342 343 `app.fire()` do:344 117 unmodified lines