import { parseBody } from './utils/body.ts' import type { Body } from './utils/body.ts' import type { Cookie } from './utils/cookie.ts' import { parse } from './utils/cookie.ts' declare global { interface Request { param: { (key: ParamKeyType): string (): Record } paramData?: Record query: { (key: string): string (): Record } queries: { (key: string): string[] (): Record } header: { (name: string): string (): Record } cookie: { (name: string): string (): Cookie } parsedBody?: Promise parseBody: { (): Promise } } } export function extendRequestPrototype() { if (!!Request.prototype.param as boolean) { // already extended return } Request.prototype.param = function (this: Request, key?: string) { if (this.paramData) { if (key) { return this.paramData[key] } else { return this.paramData } } return null } as InstanceType['param'] Request.prototype.header = function (this: Request, name?: string) { if (name) { return this.headers.get(name) } else { const result: Record = {} for (const [key, value] of this.headers) { result[key] = value } return result } } as InstanceType['header'] Request.prototype.query = function (this: Request, key?: string) { const url = new URL(this.url) if (key) { return url.searchParams.get(key) } else { const result: Record = {} for (const key of url.searchParams.keys()) { result[key] = url.searchParams.get(key) || '' } return result } } as InstanceType['query'] Request.prototype.queries = function (this: Request, key?: string) { const url = new URL(this.url) if (key) { return url.searchParams.getAll(key) } else { const result: Record = {} for (const key of url.searchParams.keys()) { result[key] = url.searchParams.getAll(key) } return result } } as InstanceType['queries'] Request.prototype.cookie = function (this: Request, key?: string) { const cookie = this.headers.get('Cookie') || '' const obj = parse(cookie) if (key) { const value = obj[key] return value } else { return obj } } as InstanceType['cookie'] Request.prototype.parseBody = function (this: Request) { if (!this.parsedBody) { this.parsedBody = parseBody(this) } return this.parsedBody } as InstanceType['parseBody'] }