microsoft/vscode-react-native
Publicmirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable
src/extension/networkInspector/requestBodyFormatters/graphQLFormatter.ts
69lines · 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 { IFormatter, decodeBody, FormattedBody } from "./requestBodyFormatter"; |
| 5 | import { OutputChannelLogger } from "../../log/OutputChannelLogger"; |
| 6 | import { Request, Response } from "../networkMessageData"; |
| 7 | import * as querystring from "querystring"; |
| 8 | |
| 9 | /** |
| 10 | * @preserve |
| 11 | * Start region: the code is borrowed from https://github.com/facebook/flipper/blob/v0.79.1/desktop/plugins/network/RequestDetails.tsx#L704-L767 |
| 12 | * |
| 13 | * Copyright (c) Facebook, Inc. and its affiliates. |
| 14 | * |
| 15 | * This source code is licensed under the MIT license found in the |
| 16 | * LICENSE file in the root directory of this source tree. |
| 17 | * |
| 18 | * @format |
| 19 | */ |
| 20 | |
| 21 | export class GraphQLFormatter implements IFormatter { |
| 22 | constructor(private logger: OutputChannelLogger) {} |
| 23 | |
| 24 | public formatRequest(request: Request, contentType: string): FormattedBody | null { |
| 25 | if (request.url.indexOf("graphql") > 0) { |
| 26 | const decoded = decodeBody(request, this.logger); |
| 27 | if (!decoded) { |
| 28 | return null; |
| 29 | } |
| 30 | const data = querystring.parse(decoded); |
| 31 | if (typeof data.variables === "string") { |
| 32 | data.variables = JSON.parse(data.variables); |
| 33 | } |
| 34 | if (typeof data.query_params === "string") { |
| 35 | data.query_params = JSON.parse(data.query_params); |
| 36 | } |
| 37 | return data; |
| 38 | } |
| 39 | return null; |
| 40 | } |
| 41 | |
| 42 | public formatResponse(response: Response, contentType: string): FormattedBody | null { |
| 43 | if ( |
| 44 | contentType.startsWith("application/json") || |
| 45 | contentType.startsWith("application/hal+json") || |
| 46 | contentType.startsWith("text/javascript") || |
| 47 | contentType.startsWith("text/html") || |
| 48 | contentType.startsWith("application/x-fb-flatbuffer") |
| 49 | ) { |
| 50 | let decoded = decodeBody(response, this.logger); |
| 51 | try { |
| 52 | const data = JSON.parse(decoded); |
| 53 | return data; |
| 54 | } catch (SyntaxError) { |
| 55 | // Multiple top level JSON roots, map them one by one |
| 56 | return decoded |
| 57 | .replace(/}{/g, "}\r\n{") |
| 58 | .split("\n") |
| 59 | .map(json => JSON.parse(json)); |
| 60 | } |
| 61 | } |
| 62 | return null; |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | /** |
| 67 | * @preserve |
| 68 | * End region: https://github.com/facebook/flipper/blob/v0.79.1/desktop/plugins/network/RequestDetails.tsx#L704-L767 |
| 69 | */ |
| 70 | |