0
0
mirror of https://github.com/honojs/hono.git synced 2024-11-29 17:46:30 +01:00
hono/deno_dist/request.ts

108 lines
2.7 KiB
TypeScript
Raw Normal View History

2022-07-12 16:25:47 +02:00
import { parseBody } from './utils/body.ts'
2022-07-10 17:17:29 +02:00
import type { Cookie } from './utils/cookie.ts'
import { parse } from './utils/cookie.ts'
2022-07-02 08:09:45 +02:00
declare global {
interface Request<ParamKeyType extends string = string> {
param: {
(key: ParamKeyType): string
(): Record<ParamKeyType, string>
}
paramData?: Record<ParamKeyType, string>
query: {
(key: string): string
(): Record<string, string>
}
queries: {
(key: string): string[]
(): Record<string, string[]>
}
header: {
(name: string): string
(): Record<string, string>
}
2022-07-10 17:17:29 +02:00
cookie: {
(name: string): string
(): Cookie
}
2022-07-12 16:25:47 +02:00
parsedBody?: Promise<any>
parseBody: {
(): Promise<any>
}
2022-07-02 08:09:45 +02:00
}
}
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<typeof Request>['param']
Request.prototype.header = function (this: Request, name?: string) {
if (name) {
return this.headers.get(name)
} else {
const result: Record<string, string> = {}
for (const [key, value] of this.headers) {
result[key] = value
}
return result
}
} as InstanceType<typeof Request>['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<string, string> = {}
for (const key of url.searchParams.keys()) {
result[key] = url.searchParams.get(key) || ''
}
return result
}
} as InstanceType<typeof Request>['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<string, string[]> = {}
for (const key of url.searchParams.keys()) {
result[key] = url.searchParams.getAll(key)
}
return result
}
} as InstanceType<typeof Request>['queries']
2022-07-10 17:17:29 +02:00
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<typeof Request>['cookie']
2022-07-12 16:25:47 +02:00
Request.prototype.parseBody = function (this: Request) {
if (!this.parsedBody) {
this.parsedBody = parseBody(this)
}
return this.parsedBody
} as InstanceType<typeof Request>['parseBody']
2022-07-02 08:09:45 +02:00
}