MCPcopy
hub / github.com/mswjs/msw / json

Method json

src/core/HttpResponse.ts:104–138  ·  view source on GitHub ↗

* 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,
  )

Source from the content-addressed store, hash-verified

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.

Callers

nothing calls this directly

Calls 2

normalizeResponseInitFunction · 0.90
toStringMethod · 0.80

Tested by

no test coverage detected