Tweaks return values of functions for request parameters. (#234)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Tweaks return values of functions for request parameters. If no arguments are specified, returns an object containing all parameters. * Add tests for app.req.param and app.req.query. * Enable to get all cookies by `c.req.cookie()`.
authored by Taku Amano · committed by GitHub · parent b314348 · Browse files · 5 files·+211 added−106 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+211 added−106 removed
- tests:+151 added−85 removed
- other:+60 added−21 removed
Provenance
- Commit
d8accbc- Tree
94a4516- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
b314348
5 files changed+211 added−106 removed
modified:src/middleware/cookie/index.test.ts+78 added-47 removed
1234565678989101112131415101117181920211213141516171819202324252122232724252629303132272834353637383929303132333435364137383943444546474849505140414243444546474849505153525354555657585960616263646566676869707172737475767778798081828384855657585960616286878889909192939495import { Hono } from '../../hono'import { cookie } from '.'
describe('Cookie Middleware', () => { const app = new Hono() app.use('/cookie', cookie()) describe('Parse cookie', () => { const apps: Record<string, Hono> = {} apps['get by name'] = (() => { const app = new Hono()
app.get('/cookie', (c) => { const yummyCookie = c.req.cookie('yummy_cookie') const tastyCookie = c.req.cookie('tasty_cookie') const res = new Response('Good cookie') res.headers.set('Yummy-Cookie', yummyCookie) res.headers.set('Tasty-Cookie', tastyCookie) return res }) app.use('/cookie', cookie())
it('Parse cookie on c.req.cookie', async () => { const req = new Request('http://localhost/cookie') const cookieString = 'yummy_cookie=choco; tasty_cookie = strawberry ' req.headers.set('Cookie', cookieString) const res = await app.request(req) app.get('/cookie', (c) => { const yummyCookie = c.req.cookie('yummy_cookie') const tastyCookie = c.req.cookie('tasty_cookie') const res = new Response('Good cookie') res.headers.set('Yummy-Cookie', yummyCookie) res.headers.set('Tasty-Cookie', tastyCookie) return res })
expect(res.headers.get('Yummy-Cookie')).toBe('choco') expect(res.headers.get('Tasty-Cookie')).toBe('strawberry') }) return app })()
app.use('/set-cookie', cookie()) apps['get all as an object'] = (() => { const app = new Hono()
app.get('/set-cookie', (c) => { c.cookie('delicious_cookie', 'macha') return c.text('Give cookie') }) app.use('/cookie', cookie())
it('Set cookie on c.cookie', async () => { const res = await app.request('http://localhost/set-cookie') expect(res.status).toBe(200) const header = res.headers.get('Set-Cookie') expect(header).toBe('delicious_cookie=macha') }) app.get('/cookie', (c) => { const { yummy_cookie: yummyCookie, tasty_cookie: tastyCookie } = c.req.cookie() const res = new Response('Good cookie') res.headers.set('Yummy-Cookie', yummyCookie) res.headers.set('Tasty-Cookie', tastyCookie) return res })
app.use('/set-cookie-complex', cookie()) return app })()
app.get('/set-cookie-complex', (c) => { c.cookie('great_cookie', 'banana', { path: '/', secure: true, domain: 'example.com', httpOnly: true, maxAge: 1000, expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)), sameSite: 'Strict', describe.each(Object.keys(apps))('%s', (name) => { const app = apps[name] it('Parse cookie on c.req.cookie', async () => { const req = new Request('http://localhost/cookie') const cookieString = 'yummy_cookie=choco; tasty_cookie = strawberry ' req.headers.set('Cookie', cookieString) const res = await app.request(req)
expect(res.headers.get('Yummy-Cookie')).toBe('choco') expect(res.headers.get('Tasty-Cookie')).toBe('strawberry') }) }) return c.text('Give cookie') })
describe('Set cookie', () => { const app = new Hono()
app.use('/set-cookie', cookie())
app.get('/set-cookie', (c) => { c.cookie('delicious_cookie', 'macha') return c.text('Give cookie') })
it('Set cookie on c.cookie', async () => { const res = await app.request('http://localhost/set-cookie') expect(res.status).toBe(200) const header = res.headers.get('Set-Cookie') expect(header).toBe('delicious_cookie=macha') })
app.use('/set-cookie-complex', cookie())
app.get('/set-cookie-complex', (c) => { c.cookie('great_cookie', 'banana', { path: '/', secure: true, domain: 'example.com', httpOnly: true, maxAge: 1000, expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)), sameSite: 'Strict', }) return c.text('Give cookie') })
it('Complex pattern', async () => { const res = await app.request('http://localhost/set-cookie-complex') expect(res.status).toBe(200) const header = res.headers.get('Set-Cookie') expect(header).toBe( 'great_cookie=banana; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict' ) it('Complex pattern', async () => { const res = await app.request('http://localhost/set-cookie-complex') expect(res.status).toBe(200) const header = res.headers.get('Set-Cookie') expect(header).toBe( 'great_cookie=banana; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict' ) }) })})modified:src/middleware/cookie/index.ts+12 added-5 removed
12345667891011121315 unmodified lines2930313230333435363334353738394041424344454648 unmodified linesimport type { Context } from '../../context'import type { Next } from '../../hono'
declare global { interface Request { cookie: (name: string) => string cookie: { (name: string): string (): Record<string, string> } }}
declare module '../../context' {15 unmodified lines}
export const cookie = () => { return async (c: Context, next: Next) => { c.req.cookie = (name: string): string => { c.req.cookie = ((name?: string): string | Record<string, string> => { const cookie = c.req.headers.get('Cookie') const obj = parse(cookie) if (name) { const value = obj[name] return value } const value = obj[name] return value } else { return obj } }) as typeof c.req.cookie c.cookie = (name: string, value: string, opt?: CookieOptions) => { const cookie = serialize(name, value, opt) c.header('Set-Cookie', cookie) }48 unmodified linesmodified:src/context.ts+25 added-8 removed
5 unmodified lines6 type Data = string | ArrayBuffer | ReadableStream7 8 export type Env = Record<string, any>9 10-export class Context<RequestParamKeyType = string, E = Env> {10+export class Context<RequestParamKeyType extends string = string, E = Env> {11 req: Request<RequestParamKeyType>12 res: Response = undefined13 env: E14 event: FetchEvent18 unmodified lines33 this._map = {}34 Object.assign(this, opts)35 }36 37- 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.header49+50+ 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 }64 65 header(name: string, value: string): void {84 unmodified linesmodified:src/hono.test.ts+73 added-38 removed
179 unmodified lines180 })181 })182 183 describe('param and query', () => {184+ const apps: Record<string, Hono> = {}185+ apps['get by name'] = (() => {184- const app = new Hono()186+ const app = new Hono()187 186- 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+ })192 191- 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+ })197 196- 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+ })202 201- 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+ })207 206- 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+ })()210 212- 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()213 218- 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+ })218 219+ app.get('/date/:date{[0-9]+}', (c) => {220+ const { date } = c.req.param()221+ return c.text(`date is ${date}`)222+ })223+224+ app.get('/search', (c) => {225+ const { name } = c.req.query()226+ return c.text(`name is ${name}`)227+ })228+229+ app.get('/add-header', (c) => {230+ const { 'x-foo': bar } = c.req.header()231+ return c.text(`foo is ${bar}`)232+ })233+234+ return app235+ })()236+237+ describe.each(Object.keys(apps))('%s', (name) => {238+ const app = apps[name]239+240+ 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+ })245+246+ 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+ })251+252+ 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+ })257+224- 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 })267 268 describe('Middleware', () => {461 unmodified linesmodified:src/hono.ts+23 added-8 removed
6 unmodified lines7 import { TrieRouter } from './router/trie-router' // Default Router8 import { getPathFromURL, mergePath } from './utils/url'9 10 declare 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 }26 18-export type Handler<RequestParamKeyType = string, E = Env> = (27+export type Handler<RequestParamKeyType extends string = string, E = Env> = (28 c: Context<RequestParamKeyType, E>,29 next: Next30 ) => Response | Promise<Response> | void | Promise<void>31 export type NotFoundHandler<E = Env> = (c: Context<string, E>) => Response180 unmodified lines212 const path = getPathFromURL(request.url, { strict: this.strict })213 const method = request.method214 215 const result = await this.matchRoute(method, path)207- request.param = (key: string): string => {208- if (result) return result.params[key]209- }216+ request.param = ((key?: string): string | Record<string, string> => {217+ if (result) {218+ if (key) {219+ return result.params[key]220+ } else {221+ return result.params222+ }223+ }224+ }) as typeof request.param225 const handlers = result ? result.handlers : [this.notFoundHandler]226 227 const c = new Context<string, E>(request, { env: env, event: event, res: undefined })228 c.notFound = () => this.notFoundHandler(c)35 unmodified lines