0
0
mirror of https://github.com/honojs/hono.git synced 2024-12-01 11:51:01 +01:00
hono/deno_dist/middleware/cookie/index.ts
Yusuke Wada a73f0d23f0
feat: Cookie Middleware and deprecate c.req.cookie() / c.cookie() (#1066)
* feat: add Cookie Middleware and deprecate `c.req.cookie()` / `c.cookie()`

* chore: denoify
2023-05-05 11:08:03 +09:00

27 lines
828 B
TypeScript

import 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 })
}