|
| 1 | +// https://fetch.spec.whatwg.org/#json |
| 2 | +type object = JSON; |
| 3 | + |
| 4 | +type body = Object; // byte stream |
| 5 | + |
| 6 | +// https://fetch.spec.whatwg.org/#bodyinit |
| 7 | +type BodyInit = Blob | BufferSource | FormData | URLSearchParams | USVString |
| 8 | + |
| 9 | +// https://fetch.spec.whatwg.org/#body |
| 10 | +interface IBody { |
| 11 | + // readonly property |
| 12 | + bodyUsed: boolean; |
| 13 | + |
| 14 | + // method |
| 15 | + arrayBuffer(): Promise<ArrayBuffer>; |
| 16 | + blob(): Promise<Blob>; |
| 17 | + formData(): Promise<FormData>; |
| 18 | + json(): Promise<JSON>; |
| 19 | + text(): Promise<USVString>; |
| 20 | +}; |
| 21 | + |
| 22 | +// https://fetch.spec.whatwg.org/#body |
| 23 | +class Body implements IBody { |
| 24 | + private _bodyUsed: boolean; |
| 25 | + private _body: body; |
| 26 | + private _usedFlag: boolean; |
| 27 | + private _mimeType: string; |
| 28 | + |
| 29 | + get bodyUsed(): boolean { |
| 30 | + return this._bodyUsed; |
| 31 | + } |
| 32 | + |
| 33 | + get body(): body { |
| 34 | + return this._body; |
| 35 | + } |
| 36 | + |
| 37 | + get usedFlag(): boolean { |
| 38 | + return this._usedFlag; |
| 39 | + } |
| 40 | + |
| 41 | + get mimeType(): string { |
| 42 | + return this._mimeType; |
| 43 | + } |
| 44 | + |
| 45 | + consumeBody(_type: string): any { |
| 46 | + // step 1 |
| 47 | + var p = new Promise((resolve, reject) => { |
| 48 | + // step 2 |
| 49 | + if (this._bodyUsed == true) { |
| 50 | + return reject(new TypeError("body was already used")); |
| 51 | + } |
| 52 | + |
| 53 | + // step 3 |
| 54 | + this._bodyUsed = true; |
| 55 | + |
| 56 | + // step 3-1 |
| 57 | + var stream = this._body; |
| 58 | + |
| 59 | + // step 3-2 |
| 60 | + if (stream == null) { |
| 61 | + stream = []; |
| 62 | + } |
| 63 | + |
| 64 | + // step 3-3 |
| 65 | + // TODO: Let bytes be the result of reading from stream until it returns end-of-stream. |
| 66 | + var bytes; |
| 67 | + |
| 68 | + // step 4 |
| 69 | + // TODO: implement me |
| 70 | + switch(_type) { |
| 71 | + case "ArrayBuffer": |
| 72 | + case "Blob": |
| 73 | + case "FormData": |
| 74 | + case "JSON": |
| 75 | + case "text": |
| 76 | + } |
| 77 | + }); |
| 78 | + return p; |
| 79 | + } |
| 80 | + |
| 81 | + arrayBuffer(): Promise<ArrayBuffer> { |
| 82 | + return this.consumeBody("ArrayBuffer"); |
| 83 | + } |
| 84 | + |
| 85 | + blob(): Promise<Blob> { |
| 86 | + return this.consumeBody("Blob"); |
| 87 | + } |
| 88 | + |
| 89 | + formData(): Promise<FormData> { |
| 90 | + return this.consumeBody("FormData"); |
| 91 | + } |
| 92 | + |
| 93 | + json(): Promise<JSON> { |
| 94 | + return this.consumeBody("JSON"); |
| 95 | + } |
| 96 | + |
| 97 | + text(): Promise<USVString> { |
| 98 | + return this.consumeBody("text"); |
| 99 | + } |
| 100 | +} |
0 commit comments