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

284 lines
8.0 KiB
TypeScript
Raw Normal View History

import { HonoRequest } from './request.ts'
import type { TypeResponse, Route } from './types.ts'
import type { Environment, NotFoundHandler } from './types.ts'
2022-07-10 17:17:29 +02:00
import type { CookieOptions } from './utils/cookie.ts'
import { serialize } from './utils/cookie.ts'
2022-07-02 08:09:45 +02:00
import type { StatusCode } from './utils/http-status.ts'
type Runtime = 'node' | 'deno' | 'bun' | 'cloudflare' | 'fastly' | 'vercel' | 'lagon' | 'other'
type HeaderField = [string, string]
type Headers = Record<string, string | string[]>
type Data = string | ArrayBuffer | ReadableStream
export interface ExecutionContext {
waitUntil(promise: Promise<void>): void
passThroughOnException(): void
}
export interface ContextVariableMap {}
2022-07-02 08:09:45 +02:00
type GetVariable<K, E extends Partial<Environment>> = K extends keyof E['Variables']
? E['Variables'][K]
: K extends keyof ContextVariableMap
? ContextVariableMap[K]
: unknown
type ContextOptions<E extends Partial<Environment>, R extends Route> = {
env?: E['Bindings']
executionCtx?: FetchEvent | ExecutionContext | undefined
notFoundHandler?: NotFoundHandler<E, R>
paramData?: Record<string, string>
}
export class Context<
E extends Partial<Environment> = Environment,
R extends Route = Route,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
I = any
> {
env: E['Bindings'] = {}
finalized: boolean = false
error: Error | undefined = undefined
private _req?: HonoRequest<R, I>
private _status: StatusCode = 200
2022-07-17 11:11:09 +02:00
private _executionCtx: FetchEvent | ExecutionContext | undefined
2022-07-02 08:09:45 +02:00
private _pretty: boolean = false
private _prettySpace: number = 2
private _map: Record<string, unknown> | undefined
private _headers: Record<string, string[]> | undefined
2022-07-02 08:09:45 +02:00
private _res: Response | undefined
private _paramData: Record<string, string> | undefined
private rawRequest: Request
private notFoundHandler: NotFoundHandler<E, R> = () => new Response()
constructor(req: Request, options?: ContextOptions<E, R>) {
this.rawRequest = req
if (options) {
this._executionCtx = options.executionCtx
this._paramData = options.paramData
this.env = options.env
if (options.notFoundHandler) {
this.notFoundHandler = options.notFoundHandler
}
}
}
get req(): HonoRequest<R, I> {
if (this._req) {
return this._req
} else {
this._req = new HonoRequest<R, I>(this.rawRequest, this._paramData)
return this._req
}
2022-07-17 11:11:09 +02:00
}
get event(): FetchEvent {
if (this._executionCtx instanceof FetchEvent) {
return this._executionCtx
2022-07-02 08:09:45 +02:00
} else {
2022-07-17 11:11:09 +02:00
throw Error('This context has no FetchEvent')
2022-07-02 08:09:45 +02:00
}
2022-07-17 11:11:09 +02:00
}
2022-07-02 08:09:45 +02:00
2022-07-17 11:11:09 +02:00
get executionCtx(): ExecutionContext {
if (this._executionCtx) {
return this._executionCtx as ExecutionContext
2022-07-17 11:11:09 +02:00
} else {
throw Error('This context has no ExecutionContext')
}
2022-07-02 08:09:45 +02:00
}
get res(): Response {
return (this._res ||= new Response('404 Not Found', { status: 404 }))
2022-07-02 08:09:45 +02:00
}
set res(_res: Response) {
this._res = _res
this.finalized = true
}
header = (name: string, value: string, options?: { append?: boolean }): void => {
2022-07-02 08:09:45 +02:00
this._headers ||= {}
const key = name.toLowerCase()
let shouldAppend = false
if (options && options.append) {
const vAlreadySet = this._headers[key]
if (vAlreadySet && vAlreadySet.length) {
shouldAppend = true
}
}
if (shouldAppend) {
this._headers[key].push(value)
} else {
this._headers[key] = [value]
}
2022-07-02 08:09:45 +02:00
if (this.finalized) {
if (shouldAppend) {
this.res.headers.append(name, value)
} else {
this.res.headers.set(name, value)
}
2022-07-02 08:09:45 +02:00
}
}
status = (status: StatusCode): void => {
2022-07-02 08:09:45 +02:00
this._status = status
}
set<Key extends keyof E['Variables'] | keyof ContextVariableMap>(
key: Key,
value: GetVariable<Key, E>
): void {
2022-07-02 08:09:45 +02:00
this._map ||= {}
this._map[key as string] = value
2022-07-02 08:09:45 +02:00
}
get<Key extends keyof E['Variables'] | keyof ContextVariableMap>(key: Key): GetVariable<Key, E> {
return this._map?.[key as string] as GetVariable<Key, E>
2022-07-02 08:09:45 +02:00
}
pretty = (prettyJSON: boolean, space: number = 2): void => {
2022-07-02 08:09:45 +02:00
this._pretty = prettyJSON
this._prettySpace = space
}
newResponse = (data: Data | null, status: StatusCode, headers: Headers = {}): Response => {
return new Response(data, {
status,
headers: this._finalizeHeaders(headers),
})
}
private _finalizeHeaders(incomingHeaders: Headers): HeaderField[] {
const finalizedHeaders: HeaderField[] = []
const headersKv = this._headers || {}
// If Response is already set
2022-07-02 08:09:45 +02:00
if (this._res) {
this._res.headers.forEach((v, k) => {
headersKv[k] = [v]
2022-07-02 08:09:45 +02:00
})
}
for (const key of Object.keys(incomingHeaders)) {
const value = incomingHeaders[key]
if (typeof value === 'string') {
finalizedHeaders.push([key, value])
} else {
for (const v of value) {
finalizedHeaders.push([key, v])
}
}
delete headersKv[key]
}
for (const key of Object.keys(headersKv)) {
for (const value of headersKv[key]) {
const kv: HeaderField = [key, value]
finalizedHeaders.push(kv)
}
}
return finalizedHeaders
2022-07-02 08:09:45 +02:00
}
body = (
data: Data | null,
status: StatusCode = this._status,
headers: Headers = {}
): Response => {
2022-07-02 08:09:45 +02:00
return this.newResponse(data, status, headers)
}
text = (text: string, status?: StatusCode, headers?: Headers): Response => {
// If the header is empty, return Response immediately.
// Content-Type will be added automatically as `text/plain`.
if (!headers && !status && !this._res && !this._headers) {
return new Response(text)
}
status ||= this._status
headers ||= {}
headers['content-type'] = 'text/plain; charset=UTF-8'
return this.newResponse(text, status, headers)
2022-07-02 08:09:45 +02:00
}
json = <T>(object: T, status: StatusCode = this._status, headers: Headers = {}): Response => {
2022-07-02 08:09:45 +02:00
const body = this._pretty
? JSON.stringify(object, null, this._prettySpace)
: JSON.stringify(object)
headers['content-type'] = 'application/json; charset=UTF-8'
return this.newResponse(body, status, headers)
2022-07-02 08:09:45 +02:00
}
<<<<<<< HEAD
html = (html: string, status: StatusCode = this._status, headers: Headers = {}): Response => {
=======
jsonT<T>(object: T, status: StatusCode = this._status, headers: Headers = {}): TypeResponse<T> {
return {
response: this.json(object, status, headers),
data: object,
format: 'json',
}
}
html(html: string, status: StatusCode = this._status, headers: Headers = {}): Response {
>>>>>>> fee7292 (feat: new validator middleware using 3rd-party & current middleware obsolete (#745))
headers['content-type'] = 'text/html; charset=UTF-8'
return this.newResponse(html, status, headers)
2022-07-02 08:09:45 +02:00
}
redirect = (location: string, status: StatusCode = 302): Response => {
2022-07-02 08:09:45 +02:00
return this.newResponse(null, status, {
Location: location,
})
}
cookie = (name: string, value: string, opt?: CookieOptions): void => {
2022-07-10 17:17:29 +02:00
const cookie = serialize(name, value, opt)
this.header('set-cookie', cookie, { append: true })
2022-07-10 17:17:29 +02:00
}
<<<<<<< HEAD
notFound = (): Response | Promise<Response> => {
return this.notFoundHandler(this as unknown as Context<string, E>)
=======
notFound(): Response | Promise<Response> {
return this.notFoundHandler(this)
>>>>>>> fee7292 (feat: new validator middleware using 3rd-party & current middleware obsolete (#745))
2022-07-02 08:09:45 +02:00
}
get runtime(): Runtime {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const global = globalThis as any
if (global?.Deno !== undefined) {
return 'deno'
}
if (global?.Bun !== undefined) {
return 'bun'
}
if (typeof global?.WebSocketPair === 'function') {
return 'cloudflare'
}
if (global?.fastly !== undefined) {
return 'fastly'
}
if (typeof global?.EdgeRuntime === 'string') {
return 'vercel'
}
if (global?.process?.release?.name === 'node') {
return 'node'
}
if (global?.__lagon__ !== undefined) {
return 'lagon'
}
return 'other'
}
2022-07-02 08:09:45 +02:00
}