Skip to content

Commit

Permalink
refactor: response
Browse files Browse the repository at this point in the history
  • Loading branch information
ariskemper committed Feb 1, 2024
1 parent 5490018 commit 42d4342
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 22 deletions.
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@
],
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
}
},
"typescript.tsdk": "node_modules/typescript/lib"
}
52 changes: 31 additions & 21 deletions src/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,39 +12,49 @@ export class Response {
#body?: BodyInit | null
#init?: ResponseInit

constructor(body?: BodyInit | null, init?: ResponseInit) {
this.#body = body

if (init instanceof Response) {
this.handleResponseInitFromAnotherResponse(init)
} else {
this.#init = init
}

this.handleBodyStringOrStream(body, init)
}

private get cache(): typeof GlobalResponse {
delete (this as any)[cacheKey]
return ((this as any)[responseCache] ||= new GlobalResponse(this.#body, this.#init))
}

constructor(body?: BodyInit | null, init?: ResponseInit) {
this.#body = body
if (init instanceof Response) {
const cachedGlobalResponse = (init as any)[responseCache]
if (cachedGlobalResponse) {
this.#init = cachedGlobalResponse
// instantiate GlobalResponse cache and this object always returns value from global.Response
this.cache
return
} else {
this.#init = init.#init
}
private handleResponseInitFromAnotherResponse(init: Response): void {
const cachedGlobalResponse = (init as any)[responseCache]

if (cachedGlobalResponse) {
this.#init = cachedGlobalResponse
this.cache
} else {
this.#init = init
this.#init = init.#init
}
}

if (typeof body === 'string' || body instanceof ReadableStream) {
let headers = (init?.headers || { 'content-type': 'text/plain;charset=UTF-8' }) as
| Record<string, string>
| Headers
| OutgoingHttpHeaders
if (headers instanceof Headers) {
headers = buildOutgoingHttpHeaders(headers)
}
private handleBodyStringOrStream(body?: BodyInit | null, init?: ResponseInit): void {
const headers = this.buildHeaders(init?.headers)

if (typeof body === 'string' || body instanceof ReadableStream) {
;(this as any)[cacheKey] = [init?.status || 200, body, headers]
}
}

private buildHeaders(headers?: HeadersInit): HeadersInit | OutgoingHttpHeaders {
if (headers instanceof Headers) {
return buildOutgoingHttpHeaders(headers)
}

return headers || { 'content-type': 'text/plain;charset=UTF-8' }
}
}
;[
'body',
Expand Down

0 comments on commit 42d4342

Please sign in to comment.