microsoft/vscode-react-native
Publicmirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable
src/extension/networkInspector/requestBodyFormatters/jsonFormatter.ts
52lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | // Licensed under the MIT license. See LICENSE file in the project root for details. |
| 3 | |
| 4 | import { OutputChannelLogger } from "../../log/OutputChannelLogger"; |
| 5 | import { Request, Response } from "../networkMessageData"; |
| 6 | import { IFormatter, decodeBody, FormattedBody } from "./requestBodyFormatter"; |
| 7 | |
| 8 | /** |
| 9 | * @preserve |
| 10 | * Start region: the code is borrowed from https://github.com/facebook/flipper/blob/v0.79.1/desktop/plugins/network/RequestDetails.tsx#L609-L653 |
| 11 | * |
| 12 | * Copyright (c) Facebook, Inc. and its affiliates. |
| 13 | * |
| 14 | * This source code is licensed under the MIT license found in the |
| 15 | * LICENSE file in the root directory of this source tree. |
| 16 | * |
| 17 | * @format |
| 18 | */ |
| 19 | |
| 20 | export class JSONFormatter implements IFormatter { |
| 21 | constructor(private logger: OutputChannelLogger) {} |
| 22 | |
| 23 | public formatRequest(request: Request, contentType: string): FormattedBody | null { |
| 24 | return this.format(decodeBody(request, this.logger), contentType); |
| 25 | } |
| 26 | |
| 27 | public formatResponse(response: Response, contentType: string): FormattedBody | null { |
| 28 | return this.format(decodeBody(response, this.logger), contentType); |
| 29 | } |
| 30 | |
| 31 | private format(body: string, contentType: string): FormattedBody | null { |
| 32 | if ( |
| 33 | contentType.startsWith("application/json") || |
| 34 | contentType.startsWith("application/hal+json") || |
| 35 | contentType.startsWith("text/javascript") || |
| 36 | contentType.startsWith("application/x-fb-flatbuffer") |
| 37 | ) { |
| 38 | try { |
| 39 | return JSON.parse(body); |
| 40 | } catch (SyntaxError) { |
| 41 | // Multiple top level JSON roots, map them one by one |
| 42 | return body.split("\n").map(json => JSON.parse(json)); |
| 43 | } |
| 44 | } |
| 45 | return null; |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * @preserve |
| 51 | * End region: https://github.com/facebook/flipper/blob/v0.79.1/desktop/plugins/network/RequestDetails.tsx#L609-L653 |
| 52 | */ |
| 53 | |