|
1 | 1 | import { compress as brotli } from 'https://deno.land/x/[email protected]/mod.ts'
|
| 2 | +import { FormDataReader } from 'https://deno.land/x/[email protected]/multipart.ts' |
2 | 3 | import { gzipEncode } from 'https://deno.land/x/[email protected]/mod.ts'
|
3 | 4 | import log from './log.ts'
|
4 | 5 | import { ServerRequest } from './std.ts'
|
5 |
| -import type { APIRequest } from './types.ts' |
| 6 | +import type { APIRequest, FormDataBody } from './types.ts' |
6 | 7 |
|
7 | 8 | export class Request extends ServerRequest implements APIRequest {
|
8 | 9 | #pathname: string
|
@@ -84,6 +85,51 @@ export class Request extends ServerRequest implements APIRequest {
|
84 | 85 | await this.send(JSON.stringify(data, replacer, space), 'application/json; charset=utf-8')
|
85 | 86 | }
|
86 | 87 |
|
| 88 | + async decodeBody(type: "text"): Promise<string> |
| 89 | + async decodeBody(type: "json"): Promise<any> |
| 90 | + async decodeBody(type: "form-data"): Promise<FormDataBody> |
| 91 | + async decodeBody(type: string): Promise<any> { |
| 92 | + if (type === "text") { |
| 93 | + try { |
| 94 | + const buff: Uint8Array = await Deno.readAll(this.body); |
| 95 | + const encoded = new TextDecoder("utf-8").decode(buff); |
| 96 | + return encoded; |
| 97 | + } catch (err) { |
| 98 | + console.error("Failed to parse the request body.", err); |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + if (type === "json") { |
| 103 | + try { |
| 104 | + const buff: Uint8Array = await Deno.readAll(this.body); |
| 105 | + const encoded = new TextDecoder("utf-8").decode(buff); |
| 106 | + const json = JSON.parse(encoded); |
| 107 | + return json; |
| 108 | + } catch (err) { |
| 109 | + console.error("Failed to parse the request body.", err); |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + if (type === "form-data") { |
| 114 | + try { |
| 115 | + const boundary = this.headers.get("content-type"); |
| 116 | + |
| 117 | + if (!boundary) throw new Error("Failed to get the content-type") |
| 118 | + |
| 119 | + const reader = new FormDataReader(boundary, this.body); |
| 120 | + const { fields, files } = await reader.read({ maxSize: 1024 * 1024 * 10 }); |
| 121 | + |
| 122 | + return { |
| 123 | + get: (key: string) => fields[key], |
| 124 | + getFile: (key: string) => files?.find(i => i.name === key) |
| 125 | + } |
| 126 | + |
| 127 | + } catch (err) { |
| 128 | + console.error("Failed to parse the request form-data", err) |
| 129 | + } |
| 130 | + } |
| 131 | + } |
| 132 | + |
87 | 133 | async send(data: string | Uint8Array | ArrayBuffer, contentType?: string): Promise<void> {
|
88 | 134 | if (this.#resp.done) {
|
89 | 135 | log.warn('ServerRequest: repeat respond calls')
|
|
0 commit comments