response-polyfill.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. class ResponsePolyfill {
  2. constructor(
  3. public body: string | ArrayBuffer | null,
  4. public init: {
  5. status?: number
  6. statusText?: string
  7. headers?: Record<string, string>
  8. } = {}
  9. ) {}
  10. get ok(): boolean {
  11. return this.status >= 200 && this.status < 300
  12. }
  13. get status(): number {
  14. return this.init.status || 200
  15. }
  16. get statusText(): string {
  17. return this.init.statusText || 'OK'
  18. }
  19. get headers(): Headers {
  20. return new Headers(this.init.headers || {})
  21. }
  22. get bodyUsed(): boolean {
  23. return false // 小程序环境简单实现
  24. }
  25. async arrayBuffer(): Promise<ArrayBuffer> {
  26. if (this.body instanceof ArrayBuffer) {
  27. return this.body
  28. }
  29. throw new Error('Not implemented')
  30. }
  31. async text(): Promise<string> {
  32. if (typeof this.body === 'string') {
  33. return this.body
  34. }
  35. throw new Error('Not implemented')
  36. }
  37. async json<T = any>(): Promise<T> {
  38. if (typeof this.body === 'string') {
  39. try {
  40. return JSON.parse(this.body)
  41. } catch (e) {
  42. throw new Error('Invalid JSON')
  43. }
  44. }
  45. throw new Error('Not implemented')
  46. }
  47. clone(): ResponsePolyfill {
  48. return new ResponsePolyfill(this.body, { ...this.init })
  49. }
  50. static json(data: any, init?: ResponseInit): ResponsePolyfill {
  51. const headers = new Headers(init && 'headers' in init ? init.headers : undefined)
  52. if (!headers.has('Content-Type')) {
  53. headers.set('Content-Type', 'application/json')
  54. }
  55. return new ResponsePolyfill(JSON.stringify(data), {
  56. ...init,
  57. headers: Object.fromEntries(headers.entries())
  58. })
  59. }
  60. static error(): ResponsePolyfill {
  61. return new ResponsePolyfill(null, { status: 0, statusText: 'Network Error' })
  62. }
  63. static redirect(url: string, status: number): ResponsePolyfill {
  64. return new ResponsePolyfill(null, {
  65. status,
  66. headers: { Location: url }
  67. })
  68. }
  69. }
  70. // 全局注册(如果需要)
  71. if (typeof globalThis.Response === 'undefined') {
  72. globalThis.Response = ResponsePolyfill as any
  73. }
  74. export default ResponsePolyfill