feat: support appending values with `c.header` (#539)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Yusuke Wada · committed by GitHub · parent 2a80b58 · Browse files · 5 files·+142 added−27 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+142 added−27 removed
- tests:+29 added−0 removed
- other:+113 added−27 removed
Provenance
- Commit
5133a93- Tree
e1fb4ca- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
2a80b58
5 files changed+142 added−27 removed
modified:deno_dist/utils/encode.ts+1 added-1 removed
11234572 unmodified linesimport { Buffer } from "https://deno.land/std@0.155.0/node/buffer.ts";import { Buffer } from "https://deno.land/std@0.156.0/node/buffer.ts";export const encodeBase64 = (str: string): string => { if (str === null) { throw new TypeError('1st argument of "encodeBase64" should not be null.') }72 unmodified linesmodified:deno_dist/context.ts+56 added-13 removed
8 unmodified lines9 import type { CookieOptions } from './utils/cookie.ts'10 import { serialize } from './utils/cookie.ts'11 import type { StatusCode } from './utils/http-status.ts'12 13-type Headers = Record<string, string>13+type HeaderField = [string, string]14+type Headers = Record<string, string | string[]>15 export type Data = string | ArrayBuffer | ReadableStream16 17 export interface Context<18 RequestParamKeyType extends string = string,7 unmodified lines26 finalized: boolean27 28 get res(): Response29 set res(_res: Response)29- header: (name: string, value: string) => void30+ header: (name: string, value: string, options?: { append?: boolean }) => void31 status: (status: StatusCode) => void32 set: {33 <Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void34 <Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void29 unmodified lines64 private _executionCtx: FetchEvent | ExecutionContext | undefined65 private _pretty: boolean = false66 private _prettySpace: number = 267 private _map: Record<string, any> | undefined67- private _headers: Record<string, string> | undefined68+ private _headers: Record<string, string[]> | undefined69 private _res: Response | undefined70 private notFoundHandler: NotFoundHandler<E>71 72 constructor(34 unmodified lines107 this._res = _res108 this.finalized = true109 }110 110- header(name: string, value: string): void {111+ header(name: string, value: string, options?: { append?: boolean }): void {112 this._headers ||= {}112- this._headers[name.toLowerCase()] = value113+ const key = name.toLowerCase()114+115+ let shouldAppend = false116+ if (options && options.append) {117+ const vAlreadySet = this._headers[key]118+ if (vAlreadySet && vAlreadySet.length) {119+ shouldAppend = true120+ }121+ }122+123+ if (shouldAppend) {124+ this._headers[key].push(value)125+ } else {126+ this._headers[key] = [value]127+ }128+129 if (this.finalized) {130+ if (shouldAppend) {131+ this.res.headers.append(name, value)132+ } else {114- this.res.headers.set(name, value)133+ this.res.headers.set(name, value)134+ }135 }136 }137 138 status(status: StatusCode): void {23 unmodified lines162 this._prettySpace = space163 }164 165 newResponse(data: Data | null, status: StatusCode, headers: Headers = {}): Response {146- const _headers = { ...this._headers }166+ return new Response(data, {167+ status: status || this._status || 200,168+ headers: this._finalizeHeaders(headers),169+ })170+ }171+172+ private _finalizeHeaders(incomingHeaders: Headers): HeaderField[] {173+ const finalizedHeaders: HeaderField[] = []174+ const headersKv = this._headers || {}175+ // If Response is already set176 if (this._res) {177 this._res.headers.forEach((v, k) => {149- _headers[k] = v178+ headersKv[k] = [v]179 })180 }152- return new Response(data, {153- status: status || this._status || 200,154- headers: { ..._headers, ...headers },155- })181+ for (const key of Object.keys(incomingHeaders)) {182+ const value = incomingHeaders[key]183+ if (typeof value === 'string') {184+ finalizedHeaders.push([key, value])185+ } else {186+ for (const v of value) {187+ finalizedHeaders.push([key, v])188+ }189+ }190+ delete headersKv[key]191+ }192+ for (const key of Object.keys(headersKv)) {193+ for (const value of headersKv[key]) {194+ const kv: HeaderField = [key, value]195+ finalizedHeaders.push(kv)196+ }197+ }198+ return finalizedHeaders199 }200 201 body(data: Data | null, status: StatusCode = this._status, headers: Headers = {}): Response {202 return this.newResponse(data, status, headers)24 unmodified lines227 }228 229 cookie(name: string, value: string, opt?: CookieOptions): void {230 const cookie = serialize(name, value, opt)188- this.header('set-cookie', cookie)231+ this.header('set-cookie', cookie, { append: true })232 }233 234 notFound(): Response | Promise<Response> {235 return this.notFoundHandler(this as any)2 unmodified linesmodified:src/context.test.ts+16 added
66 unmodified lines67 const foo = res.headers.get('X-Foo')68 expect(foo).toBe('Bar')69 })70 71+ it('c.header() - append', async () => {72+ c.header('X-Foo', 'Bar')73+ c.header('X-Foo', 'Buzz', { append: true })74+ const res = c.body('Hi')75+ const foo = res.headers.get('X-Foo')76+ expect(foo).toBe('Bar, Buzz')77+ })78+79+ it('c.body() - multiple header', async () => {80+ const res = c.body('Hi', 200, {81+ 'X-Foo': ['Bar', 'Buzz'],82+ })83+ const foo = res.headers.get('X-Foo')84+ expect(foo).toBe('Bar, Buzz')85+ })86+87 it('c.status()', async () => {88 c.status(201)89 const res = c.body('Hi')90 expect(res.status).toBe(201)92 unmodified linesmodified:src/context.ts+56 added-13 removed
8 unmodified lines9 import type { CookieOptions } from './utils/cookie'10 import { serialize } from './utils/cookie'11 import type { StatusCode } from './utils/http-status'12 13-type Headers = Record<string, string>13+type HeaderField = [string, string]14+type Headers = Record<string, string | string[]>15 export type Data = string | ArrayBuffer | ReadableStream16 17 export interface Context<18 RequestParamKeyType extends string = string,7 unmodified lines26 finalized: boolean27 28 get res(): Response29 set res(_res: Response)29- header: (name: string, value: string) => void30+ header: (name: string, value: string, options?: { append?: boolean }) => void31 status: (status: StatusCode) => void32 set: {33 <Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void34 <Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void29 unmodified lines64 private _executionCtx: FetchEvent | ExecutionContext | undefined65 private _pretty: boolean = false66 private _prettySpace: number = 267 private _map: Record<string, any> | undefined67- private _headers: Record<string, string> | undefined68+ private _headers: Record<string, string[]> | undefined69 private _res: Response | undefined70 private notFoundHandler: NotFoundHandler<E>71 72 constructor(34 unmodified lines107 this._res = _res108 this.finalized = true109 }110 110- header(name: string, value: string): void {111+ header(name: string, value: string, options?: { append?: boolean }): void {112 this._headers ||= {}112- this._headers[name.toLowerCase()] = value113+ const key = name.toLowerCase()114+115+ let shouldAppend = false116+ if (options && options.append) {117+ const vAlreadySet = this._headers[key]118+ if (vAlreadySet && vAlreadySet.length) {119+ shouldAppend = true120+ }121+ }122+123+ if (shouldAppend) {124+ this._headers[key].push(value)125+ } else {126+ this._headers[key] = [value]127+ }128+129 if (this.finalized) {130+ if (shouldAppend) {131+ this.res.headers.append(name, value)132+ } else {114- this.res.headers.set(name, value)133+ this.res.headers.set(name, value)134+ }135 }136 }137 138 status(status: StatusCode): void {23 unmodified lines162 this._prettySpace = space163 }164 165 newResponse(data: Data | null, status: StatusCode, headers: Headers = {}): Response {146- const _headers = { ...this._headers }166+ return new Response(data, {167+ status: status || this._status || 200,168+ headers: this._finalizeHeaders(headers),169+ })170+ }171+172+ private _finalizeHeaders(incomingHeaders: Headers): HeaderField[] {173+ const finalizedHeaders: HeaderField[] = []174+ const headersKv = this._headers || {}175+ // If Response is already set176 if (this._res) {177 this._res.headers.forEach((v, k) => {149- _headers[k] = v178+ headersKv[k] = [v]179 })180 }152- return new Response(data, {153- status: status || this._status || 200,154- headers: { ..._headers, ...headers },155- })181+ for (const key of Object.keys(incomingHeaders)) {182+ const value = incomingHeaders[key]183+ if (typeof value === 'string') {184+ finalizedHeaders.push([key, value])185+ } else {186+ for (const v of value) {187+ finalizedHeaders.push([key, v])188+ }189+ }190+ delete headersKv[key]191+ }192+ for (const key of Object.keys(headersKv)) {193+ for (const value of headersKv[key]) {194+ const kv: HeaderField = [key, value]195+ finalizedHeaders.push(kv)196+ }197+ }198+ return finalizedHeaders199 }200 201 body(data: Data | null, status: StatusCode = this._status, headers: Headers = {}): Response {202 return this.newResponse(data, status, headers)24 unmodified lines227 }228 229 cookie(name: string, value: string, opt?: CookieOptions): void {230 const cookie = serialize(name, value, opt)188- this.header('set-cookie', cookie)231+ this.header('set-cookie', cookie, { append: true })232 }233 234 notFound(): Response | Promise<Response> {235 return this.notFoundHandler(this as any)2 unmodified linesmodified:src/hono.test.ts+13 added
986 unmodified lines987 expect(header).toBe(988 'great_cookie=banana; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict'989 )990 })991+992+ app.get('/set-cookie-multiple', (c) => {993+ c.cookie('delicious_cookie', 'macha')994+ c.cookie('delicious_cookie', 'choco')995+ return c.text('Give cookie')996+ })997+998+ it('Multiple values', async () => {999+ const res = await app.request('http://localhost/set-cookie-multiple')1000+ expect(res.status).toBe(200)1001+ const header = res.headers.get('Set-Cookie')1002+ expect(header).toBe('delicious_cookie=macha, delicious_cookie=choco')1003+ })1004 })1005 })1006 1007 describe('Parse Body', () => {108 unmodified lines