Skip to content
Myr

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

5 files+142 added−27 removed

modified:deno_dist/utils/encode.ts+1 added-1 removed
modified:deno_dist/context.ts+56 added-13 removed
8 unmodified lines
9import type { CookieOptions } from './utils/cookie.ts'10import { serialize } from './utils/cookie.ts'11import type { StatusCode } from './utils/http-status.ts'1213type Headers = Record<string, string>13type HeaderField = [string, string]14type Headers = Record<string, string | string[]>15export type Data = string | ArrayBuffer | ReadableStream1617export interface Context<18 RequestParamKeyType extends string = string,
7 unmodified lines
26 finalized: boolean2728 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]): void
29 unmodified lines
64 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>7172 constructor(
34 unmodified lines
107 this._res = _res108 this.finalized = true109 }110110 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()114115 let shouldAppend = false116 if (options && options.append) {117 const vAlreadySet = this._headers[key]118 if (vAlreadySet && vAlreadySet.length) {119 shouldAppend = true120 }121 }122123 if (shouldAppend) {124 this._headers[key].push(value)125 } else {126 this._headers[key] = [value]127 }128129 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 }137138 status(status: StatusCode): void {
23 unmodified lines
162 this._prettySpace = space163 }164165 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 }171172 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 }200201 body(data: Data | null, status: StatusCode = this._status, headers: Headers = {}): Response {202 return this.newResponse(data, status, headers)
24 unmodified lines
227 }228229 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 }233234 notFound(): Response | Promise<Response> {235 return this.notFoundHandler(this as any)
2 unmodified lines
modified:src/context.test.ts+16 added
66 unmodified lines
67 const foo = res.headers.get('X-Foo')68 expect(foo).toBe('Bar')69 })7071 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 })7879 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 })8687 it('c.status()', async () => {88 c.status(201)89 const res = c.body('Hi')90 expect(res.status).toBe(201)
92 unmodified lines
modified:src/context.ts+56 added-13 removed
8 unmodified lines
9import type { CookieOptions } from './utils/cookie'10import { serialize } from './utils/cookie'11import type { StatusCode } from './utils/http-status'1213type Headers = Record<string, string>13type HeaderField = [string, string]14type Headers = Record<string, string | string[]>15export type Data = string | ArrayBuffer | ReadableStream1617export interface Context<18 RequestParamKeyType extends string = string,
7 unmodified lines
26 finalized: boolean2728 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]): void
29 unmodified lines
64 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>7172 constructor(
34 unmodified lines
107 this._res = _res108 this.finalized = true109 }110110 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()114115 let shouldAppend = false116 if (options && options.append) {117 const vAlreadySet = this._headers[key]118 if (vAlreadySet && vAlreadySet.length) {119 shouldAppend = true120 }121 }122123 if (shouldAppend) {124 this._headers[key].push(value)125 } else {126 this._headers[key] = [value]127 }128129 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 }137138 status(status: StatusCode): void {
23 unmodified lines
162 this._prettySpace = space163 }164165 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 }171172 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 }200201 body(data: Data | null, status: StatusCode = this._status, headers: Headers = {}): Response {202 return this.newResponse(data, status, headers)
24 unmodified lines
227 }228229 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 }233234 notFound(): Response | Promise<Response> {235 return this.notFoundHandler(this as any)
2 unmodified lines
modified:src/hono.test.ts+13 added
986 unmodified lines
987 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 })991992 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 })997998 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})10061007describe('Parse Body', () => {
108 unmodified lines