export type ApiCoreHeaderValue = [string, ...string[]] | undefined export interface ApiCoreHeaders { [key: string]: ApiCoreHeaderValue } export interface ApiCoreRequestFormDataEntry { name: string value: string | File } export type ApiCoreRequestFormData = ApiCoreRequestFormDataEntry[] export interface ApiCoreRequestFile { name: string value: File } export type ApiCoreRequestFiles = ApiCoreRequestFile[] export interface ApiCoreStream { write(chunk: Buffer | string, encoding: BufferEncoding): Promise end(): Promise } /** * @description 参考 WHATWG 语义的稳定内部抽象类,适配不同环境的 HTTP 请求和响应。 */ export abstract class ApiCore { /** * @description Header names are in lowercase for consistency. */ abstract getRequestHeaders(): Promise async getRequestHeader(name: string): Promise { const headers = await this.getRequestHeaders() const headerValue = headers[name.toLowerCase()] return headerValue } /** * @description Method names are in uppercase for consistency with the standard HTTP method names. */ abstract getRequestMethod(): Promise abstract getRequestUrl(): string async getRequestPath(): Promise { const urlInString = this.getRequestUrl() const url = new URL(urlInString) const path = url.pathname return await Promise.resolve(path) } async getRequestSearch(): Promise { const urlInString = this.getRequestUrl() const url = new URL(urlInString) const search = url.search return await Promise.resolve(search) } abstract getRequestBodyText(): Promise async getRequestBodyJson(): Promise { const bodyText = await this.getRequestBodyText() if (bodyText.trim().length === 0) { return {} } return JSON.parse(bodyText) as unknown } abstract getRequestBodyFormData(): Promise async getRequestFiles(): Promise { const formData = await this.getRequestBodyFormData() const files: ApiCoreRequestFiles = [] for (const entry of formData) { if (entry.value instanceof File) { files.push({ name: entry.name, value: entry.value, }) } } return files } abstract text(data: unknown): Promise abstract json(data: unknown): Promise abstract stream(): Promise abstract error(): Promise }