feat: Cookie Middleware and deprecate `c.req.cookie()` / `c.cookie()` (#1066)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat: add Cookie Middleware and deprecate `c.req.cookie()` / `c.cookie()` * chore: denoify
authored by Yusuke Wada · committed by GitHub · parent 177c1a4 · Browse files · 10 files·+228 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+228 added−0 removed
- tests:+102 added−0 removed
- other:+126 added−0 removed
Provenance
- Commit
a73f0d2- Tree
2cefa42- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
177c1a4
10 files changed+228 added−0 removed
added:deno_dist/middleware/cookie/index.ts+26 added
1234567891011121314151617181920212223242526import type { Context } from '../../context.ts'import { parse, serialize } from '../../utils/cookie.ts'import type { CookieOptions, Cookie } from '../../utils/cookie.ts'
interface GetCookie { (c: Context, key: string): string | undefined (c: Context): Cookie}
export const getCookie: GetCookie = (c, key?) => { const cookie = c.req.raw.headers.get('Cookie') if (typeof key === 'string') { if (!cookie) return undefined const obj = parse(cookie) return obj[key] } if (!cookie) return {} const obj = parse(cookie) // eslint-disable-next-line @typescript-eslint/no-explicit-any return obj as any}
export const setCookie = (c: Context, name: string, value: string, opt?: CookieOptions): void => { const cookie = serialize(name, value, opt) c.header('set-cookie', cookie, { append: true })}modified:deno_dist/context.ts+12 added
327 unmodified lines328 this._headers.set('Location', location)329 return this.newResponse(null, status)330 }331 332+ /** @deprecated333+ * Use Cookie Middleware instead of `c.cookie()`. The `c.cookie()` will be removed in v4.334+ *335+ * @example336+ *337+ * import { setCookie } from 'hono/cookie'338+ * // ...339+ * app.get('/', (c) => {340+ * setCookie(c, 'key', 'value')341+ * //...342+ * })343+ */344 cookie = (name: string, value: string, opt?: CookieOptions): void => {345 const cookie = serialize(name, value, opt)346 this.header('set-cookie', cookie, { append: true })347 }42 unmodified linesmodified:deno_dist/middleware.ts+1 added
1234567896 unmodified lines// Middlewareexport * from './middleware/basic-auth/index.ts'export * from './middleware/bearer-auth/index.ts'export * from './middleware/cache/index.ts'export * from './middleware/cookie/index.ts'export * from './middleware/compress/index.ts'export * from './middleware/cors/index.ts'export * from './middleware/etag/index.ts'export * from './middleware/html/index.ts'6 unmodified linesmodified:deno_dist/request.ts+20 added
77 unmodified lines78 }79 return headerData[name.toLowerCase()]80 }81 82+ /** @deprecated83+ * Use Cookie Middleware instead of `c.req.cookie()`. The `c.req.cookie()` will be removed in v4.84+ *85+ * @example86+ *87+ * import { getCookie } from 'hono/cookie'88+ * // ...89+ * app.get('/', (c) => c.text(getCookie(c, 'cookie-name')))90+ */91 cookie(key: string): string | undefined92+93+ /** @deprecated94+ * Use Cookie Middleware instead of `c.req.cookie()`. The `c.req.cookie()` will be removed in v4.95+ *96+ * @example97+ *98+ * import { getCookie } from 'hono/cookie'99+ * // ...100+ * app.get('/', (c) => c.json(getCookie(c)))101+ */102 cookie(): Cookie103+104 cookie(key?: string) {105 const cookie = this.raw.headers.get('Cookie')106 if (!cookie) return107 const obj = parse(cookie)94 unmodified linesadded:src/middleware/cookie/index.test.ts+102 added
1+import { Hono } from '../../hono'2+import { getCookie, setCookie } from '.'3+4+describe('Cookie Middleware', () => {5+ describe('Parse cookie', () => {6+ const apps: Record<string, Hono> = {}7+ apps['get by name'] = (() => {8+ const app = new Hono()9+10+ app.get('/cookie', (c) => {11+ const yummyCookie = getCookie(c, 'yummy_cookie')12+ const tastyCookie = getCookie(c, 'tasty_cookie')13+ const res = new Response('Good cookie')14+ if (yummyCookie && tastyCookie) {15+ res.headers.set('Yummy-Cookie', yummyCookie)16+ res.headers.set('Tasty-Cookie', tastyCookie)17+ }18+ return res19+ })20+21+ return app22+ })()23+24+ apps['get all as an object'] = (() => {25+ const app = new Hono()26+27+ app.get('/cookie', (c) => {28+ const { yummy_cookie: yummyCookie, tasty_cookie: tastyCookie } = getCookie(c)29+ const res = new Response('Good cookie')30+ res.headers.set('Yummy-Cookie', yummyCookie)31+ res.headers.set('Tasty-Cookie', tastyCookie)32+ return res33+ })34+35+ return app36+ })()37+38+ describe.each(Object.keys(apps))('%s', (name) => {39+ const app = apps[name]40+ it('Parse cookie with getCookie()', async () => {41+ const req = new Request('http://localhost/cookie')42+ const cookieString = 'yummy_cookie=choco; tasty_cookie = strawberry'43+ req.headers.set('Cookie', cookieString)44+ const res = await app.request(req)45+46+ expect(res.headers.get('Yummy-Cookie')).toBe('choco')47+ expect(res.headers.get('Tasty-Cookie')).toBe('strawberry')48+ })49+ })50+ })51+52+ describe('Set cookie', () => {53+ const app = new Hono()54+55+ app.get('/set-cookie', (c) => {56+ setCookie(c, 'delicious_cookie', 'macha')57+ return c.text('Give cookie')58+ })59+60+ it('Set cookie with setCookie()', async () => {61+ const res = await app.request('http://localhost/set-cookie')62+ expect(res.status).toBe(200)63+ const header = res.headers.get('Set-Cookie')64+ expect(header).toBe('delicious_cookie=macha')65+ })66+67+ app.get('/set-cookie-complex', (c) => {68+ setCookie(c, 'great_cookie', 'banana', {69+ path: '/',70+ secure: true,71+ domain: 'example.com',72+ httpOnly: true,73+ maxAge: 1000,74+ expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)),75+ sameSite: 'Strict',76+ })77+ return c.text('Give cookie')78+ })79+80+ it('Complex pattern', async () => {81+ const res = await app.request('http://localhost/set-cookie-complex')82+ expect(res.status).toBe(200)83+ const header = res.headers.get('Set-Cookie')84+ expect(header).toBe(85+ 'great_cookie=banana; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict'86+ )87+ })88+89+ app.get('/set-cookie-multiple', (c) => {90+ setCookie(c, 'delicious_cookie', 'macha')91+ setCookie(c, 'delicious_cookie', 'choco')92+ return c.text('Give cookie')93+ })94+95+ it('Multiple values', async () => {96+ const res = await app.request('http://localhost/set-cookie-multiple')97+ expect(res.status).toBe(200)98+ const header = res.headers.get('Set-Cookie')99+ expect(header).toBe('delicious_cookie=macha, delicious_cookie=choco')100+ })101+ })102+})added:src/middleware/cookie/index.ts+26 added
1234567891011121314151617181920212223242526import type { Context } from '../../context'import { parse, serialize } from '../../utils/cookie'import type { CookieOptions, Cookie } from '../../utils/cookie'
interface GetCookie { (c: Context, key: string): string | undefined (c: Context): Cookie}
export const getCookie: GetCookie = (c, key?) => { const cookie = c.req.raw.headers.get('Cookie') if (typeof key === 'string') { if (!cookie) return undefined const obj = parse(cookie) return obj[key] } if (!cookie) return {} const obj = parse(cookie) // eslint-disable-next-line @typescript-eslint/no-explicit-any return obj as any}
export const setCookie = (c: Context, name: string, value: string, opt?: CookieOptions): void => { const cookie = serialize(name, value, opt) c.header('set-cookie', cookie, { append: true })}modified:src/context.ts+12 added
340 unmodified lines341 this._headers.set('Location', location)342 return this.newResponse(null, status)343 }344 345+ /** @deprecated346+ * Use Cookie Middleware instead of `c.cookie()`. The `c.cookie()` will be removed in v4.347+ *348+ * @example349+ *350+ * import { setCookie } from 'hono/cookie'351+ * // ...352+ * app.get('/', (c) => {353+ * setCookie(c, 'key', 'value')354+ * //...355+ * })356+ */357 cookie = (name: string, value: string, opt?: CookieOptions): void => {358 const cookie = serialize(name, value, opt)359 this.header('set-cookie', cookie, { append: true })360 }42 unmodified linesmodified:src/middleware.ts+1 added
1234567896 unmodified lines// Middlewareexport * from './middleware/basic-auth'export * from './middleware/bearer-auth'export * from './middleware/cache'export * from './middleware/cookie'export * from './middleware/compress'export * from './middleware/cors'export * from './middleware/etag'export * from './middleware/html'6 unmodified linesmodified:src/request.ts+20 added
77 unmodified lines78 }79 return headerData[name.toLowerCase()]80 }81 82+ /** @deprecated83+ * Use Cookie Middleware instead of `c.req.cookie()`. The `c.req.cookie()` will be removed in v4.84+ *85+ * @example86+ *87+ * import { getCookie } from 'hono/cookie'88+ * // ...89+ * app.get('/', (c) => c.text(getCookie(c, 'cookie-name')))90+ */91 cookie(key: string): string | undefined92+93+ /** @deprecated94+ * Use Cookie Middleware instead of `c.req.cookie()`. The `c.req.cookie()` will be removed in v4.95+ *96+ * @example97+ *98+ * import { getCookie } from 'hono/cookie'99+ * // ...100+ * app.get('/', (c) => c.json(getCookie(c)))101+ */102 cookie(): Cookie103+104 cookie(key?: string) {105 const cookie = this.raw.headers.get('Cookie')106 if (!cookie) return107 const obj = parse(cookie)94 unmodified linesmodified:package.json+8 added
53 unmodified lines54 "types": "./dist/types/middleware/cache/index.d.ts",55 "import": "./dist/middleware/cache/index.js",56 "require": "./dist/cjs/middleware/cache/index.js"57 },58+ "./cookie": {59+ "types": "./dist/types/middleware/cookie/index.d.ts",60+ "import": "./dist/middleware/cookie/index.js",61+ "require": "./dist/cjs/middleware/cookie/index.js"62+ },63 "./compress": {64 "types": "./dist/types/middleware/compress/index.d.ts",65 "import": "./dist/middleware/compress/index.js",66 "require": "./dist/cjs/middleware/compress/index.js"132 unmodified lines199 ],200 "cache": [201 "./dist/types/middleware/cache"202 ],203+ "cookie": [204+ "./dist/types/middleware/cookie"205+ ],206 "compress": [207 "./dist/types/middleware/compress"208 ],209 "cors": [143 unmodified lines