* Create a `Response` with a `Content-Type: "application/json"` body. * @example * HttpResponse.json({ firstName: 'John' }) * HttpResponse.json({ error: 'Not Authorized' }, { status: 401 })
(
body?: NoInfer<BodyType> | null | undefined,
init?: HttpResponseInit,
)
| 102 | * HttpResponse.json({ error: 'Not Authorized' }, { status: 401 }) |
| 103 | */ |
| 104 | static json<BodyType extends JsonBodyType>( |
| 105 | body?: NoInfer<BodyType> | null | undefined, |
| 106 | init?: HttpResponseInit, |
| 107 | ): HttpResponse<BodyType> { |
| 108 | const responseInit = normalizeResponseInit(init) |
| 109 | const hasExplicitContentType = responseInit.headers.has('Content-Type') |
| 110 | |
| 111 | if (!hasExplicitContentType) { |
| 112 | responseInit.headers.set('Content-Type', 'application/json') |
| 113 | } |
| 114 | |
| 115 | /** |
| 116 | * @note TypeScript is incorrect here. |
| 117 | * Stringifying undefined will return undefined. |
| 118 | */ |
| 119 | const responseText = JSON.stringify(body) as string | undefined |
| 120 | |
| 121 | if (!responseInit.headers.has('Content-Length')) { |
| 122 | responseInit.headers.set( |
| 123 | 'Content-Length', |
| 124 | responseText ? new Blob([responseText]).size.toString() : '0', |
| 125 | ) |
| 126 | } |
| 127 | |
| 128 | const response = new HttpResponse(responseText, responseInit) |
| 129 | |
| 130 | if (!hasExplicitContentType) { |
| 131 | Object.defineProperty(response, kDefaultContentType, { |
| 132 | value: true, |
| 133 | enumerable: false, |
| 134 | }) |
| 135 | } |
| 136 | |
| 137 | return response as HttpResponse<BodyType> |
| 138 | } |
| 139 | |
| 140 | /** |
| 141 | * Create a `Response` with a `Content-Type: "application/xml"` body. |
nothing calls this directly
no test coverage detected