| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- class ResponsePolyfill {
- constructor(
- public body: string | ArrayBuffer | null,
- public init: {
- status?: number
- statusText?: string
- headers?: Record<string, string>
- } = {}
- ) {}
-
- get ok(): boolean {
- return this.status >= 200 && this.status < 300
- }
-
- get status(): number {
- return this.init.status || 200
- }
-
- get statusText(): string {
- return this.init.statusText || 'OK'
- }
-
- get headers(): Headers {
- return new Headers(this.init.headers || {})
- }
-
- get bodyUsed(): boolean {
- return false // 小程序环境简单实现
- }
-
- async arrayBuffer(): Promise<ArrayBuffer> {
- if (this.body instanceof ArrayBuffer) {
- return this.body
- }
- throw new Error('Not implemented')
- }
-
- async text(): Promise<string> {
- if (typeof this.body === 'string') {
- return this.body
- }
- throw new Error('Not implemented')
- }
-
- async json<T = any>(): Promise<T> {
- if (typeof this.body === 'string') {
- try {
- return JSON.parse(this.body)
- } catch (e) {
- throw new Error('Invalid JSON')
- }
- }
- throw new Error('Not implemented')
- }
-
- clone(): ResponsePolyfill {
- return new ResponsePolyfill(this.body, { ...this.init })
- }
-
- static json(data: any, init?: ResponseInit): ResponsePolyfill {
- const headers = new Headers(init && 'headers' in init ? init.headers : undefined)
- if (!headers.has('Content-Type')) {
- headers.set('Content-Type', 'application/json')
- }
- return new ResponsePolyfill(JSON.stringify(data), {
- ...init,
- headers: Object.fromEntries(headers.entries())
- })
- }
-
- static error(): ResponsePolyfill {
- return new ResponsePolyfill(null, { status: 0, statusText: 'Network Error' })
- }
-
- static redirect(url: string, status: number): ResponsePolyfill {
- return new ResponsePolyfill(null, {
- status,
- headers: { Location: url }
- })
- }
- }
-
- // 全局注册(如果需要)
- if (typeof globalThis.Response === 'undefined') {
- globalThis.Response = ResponsePolyfill as any
- }
-
- export default ResponsePolyfill
|