renderGraphiQL.js.flow 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. // @flow strict
  2. type GraphiQLData = {|
  3. query: ?string,
  4. variables: ?{ +[name: string]: mixed, ... },
  5. operationName: ?string,
  6. result?: mixed,
  7. options: GraphiQLOptions,
  8. |};
  9. export type GraphiQLOptions = {|
  10. /**
  11. * An optional GraphQL string to use when no query is provided and no stored
  12. * query exists from a previous session. If undefined is provided, GraphiQL
  13. * will use its own default query.
  14. */
  15. defaultQuery?: ?string,
  16. |};
  17. // Ensures string values are safe to be used within a <script> tag.
  18. function safeSerialize(data) {
  19. return data ? JSON.stringify(data).replace(/\//g, '\\/') : 'undefined';
  20. }
  21. // Implemented as Babel transformation, see ../resources/load-staticly-from-npm.js
  22. declare function loadFileStaticlyFromNPM(npmPath: string): string;
  23. /**
  24. * When express-graphql receives a request which does not Accept JSON, but does
  25. * Accept HTML, it may present GraphiQL, the in-browser GraphQL explorer IDE.
  26. *
  27. * When shown, it will be pre-populated with the result of having executed the
  28. * requested query.
  29. */
  30. export function renderGraphiQL(data: GraphiQLData): string {
  31. const queryString = data.query;
  32. const variablesString = data.variables
  33. ? JSON.stringify(data.variables, null, 2)
  34. : null;
  35. const resultString = data.result
  36. ? JSON.stringify(data.result, null, 2)
  37. : null;
  38. const operationName = data.operationName;
  39. const defaultQuery = data.options.defaultQuery;
  40. return `<!--
  41. The request to this GraphQL server provided the header "Accept: text/html"
  42. and as a result has been presented GraphiQL - an in-browser IDE for
  43. exploring GraphQL.
  44. If you wish to receive JSON, provide the header "Accept: application/json" or
  45. add "&raw" to the end of the URL within a browser.
  46. -->
  47. <!DOCTYPE html>
  48. <html>
  49. <head>
  50. <meta charset="utf-8" />
  51. <title>GraphiQL</title>
  52. <meta name="robots" content="noindex" />
  53. <meta name="referrer" content="origin" />
  54. <meta name="viewport" content="width=device-width, initial-scale=1" />
  55. <style>
  56. body {
  57. margin: 0;
  58. overflow: hidden;
  59. }
  60. #graphiql {
  61. height: 100vh;
  62. }
  63. </style>
  64. <style>
  65. // graphiql/graphiql.css
  66. ${loadFileStaticlyFromNPM('graphiql/graphiql.css')}
  67. </style>
  68. <script>
  69. // promise-polyfill/dist/polyfill.min.js
  70. ${loadFileStaticlyFromNPM('promise-polyfill/dist/polyfill.min.js')}
  71. </script>
  72. <script>
  73. // unfetch/dist/unfetch.umd.js
  74. ${loadFileStaticlyFromNPM('unfetch/dist/unfetch.umd.js')}
  75. </script>
  76. <script>
  77. // react/umd/react.production.min.js
  78. ${loadFileStaticlyFromNPM('react/umd/react.production.min.js')}
  79. </script>
  80. <script>
  81. // react-dom/umd/react-dom.production.min.js
  82. ${loadFileStaticlyFromNPM('react-dom/umd/react-dom.production.min.js')}
  83. </script>
  84. <script>
  85. // graphiql/graphiql.min.js
  86. ${loadFileStaticlyFromNPM('graphiql/graphiql.min.js')}
  87. </script>
  88. </head>
  89. <body>
  90. <div id="graphiql">Loading...</div>
  91. <script>
  92. // Collect the URL parameters
  93. var parameters = {};
  94. window.location.search.substr(1).split('&').forEach(function (entry) {
  95. var eq = entry.indexOf('=');
  96. if (eq >= 0) {
  97. parameters[decodeURIComponent(entry.slice(0, eq))] =
  98. decodeURIComponent(entry.slice(eq + 1));
  99. }
  100. });
  101. // Produce a Location query string from a parameter object.
  102. function locationQuery(params) {
  103. return '?' + Object.keys(params).filter(function (key) {
  104. return Boolean(params[key]);
  105. }).map(function (key) {
  106. return encodeURIComponent(key) + '=' +
  107. encodeURIComponent(params[key]);
  108. }).join('&');
  109. }
  110. // Derive a fetch URL from the current URL, sans the GraphQL parameters.
  111. var graphqlParamNames = {
  112. query: true,
  113. variables: true,
  114. operationName: true
  115. };
  116. var otherParams = {};
  117. for (var k in parameters) {
  118. if (parameters.hasOwnProperty(k) && graphqlParamNames[k] !== true) {
  119. otherParams[k] = parameters[k];
  120. }
  121. }
  122. var fetchURL = locationQuery(otherParams);
  123. // Defines a GraphQL fetcher using the fetch API.
  124. function graphQLFetcher(graphQLParams) {
  125. return fetch(fetchURL, {
  126. method: 'post',
  127. headers: {
  128. 'Accept': 'application/json',
  129. 'Content-Type': 'application/json'
  130. },
  131. body: JSON.stringify(graphQLParams),
  132. credentials: 'include',
  133. }).then(function (response) {
  134. return response.json();
  135. });
  136. }
  137. // When the query and variables string is edited, update the URL bar so
  138. // that it can be easily shared.
  139. function onEditQuery(newQuery) {
  140. parameters.query = newQuery;
  141. updateURL();
  142. }
  143. function onEditVariables(newVariables) {
  144. parameters.variables = newVariables;
  145. updateURL();
  146. }
  147. function onEditOperationName(newOperationName) {
  148. parameters.operationName = newOperationName;
  149. updateURL();
  150. }
  151. function updateURL() {
  152. history.replaceState(null, null, locationQuery(parameters));
  153. }
  154. // Render <GraphiQL /> into the body.
  155. ReactDOM.render(
  156. React.createElement(GraphiQL, {
  157. fetcher: graphQLFetcher,
  158. onEditQuery: onEditQuery,
  159. onEditVariables: onEditVariables,
  160. onEditOperationName: onEditOperationName,
  161. query: ${safeSerialize(queryString)},
  162. response: ${safeSerialize(resultString)},
  163. variables: ${safeSerialize(variablesString)},
  164. operationName: ${safeSerialize(operationName)},
  165. defaultQuery: ${safeSerialize(defaultQuery)},
  166. }),
  167. document.getElementById('graphiql')
  168. );
  169. </script>
  170. </body>
  171. </html>`;
  172. }