printSchema.js.flow 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. // @flow strict
  2. import objectValues from '../polyfills/objectValues';
  3. import inspect from '../jsutils/inspect';
  4. import invariant from '../jsutils/invariant';
  5. import { print } from '../language/printer';
  6. import { printBlockString } from '../language/blockString';
  7. import type { GraphQLSchema } from '../type/schema';
  8. import type { GraphQLDirective } from '../type/directives';
  9. import type {
  10. GraphQLNamedType,
  11. GraphQLScalarType,
  12. GraphQLEnumType,
  13. GraphQLObjectType,
  14. GraphQLInterfaceType,
  15. GraphQLUnionType,
  16. GraphQLInputObjectType,
  17. } from '../type/definition';
  18. import { isIntrospectionType } from '../type/introspection';
  19. import { GraphQLString, isSpecifiedScalarType } from '../type/scalars';
  20. import {
  21. DEFAULT_DEPRECATION_REASON,
  22. isSpecifiedDirective,
  23. } from '../type/directives';
  24. import {
  25. isScalarType,
  26. isObjectType,
  27. isInterfaceType,
  28. isUnionType,
  29. isEnumType,
  30. isInputObjectType,
  31. } from '../type/definition';
  32. import { astFromValue } from './astFromValue';
  33. type Options = {|
  34. /**
  35. * Descriptions are defined as preceding string literals, however an older
  36. * experimental version of the SDL supported preceding comments as
  37. * descriptions. Set to true to enable this deprecated behavior.
  38. * This option is provided to ease adoption and will be removed in v16.
  39. *
  40. * Default: false
  41. */
  42. commentDescriptions?: boolean,
  43. |};
  44. /**
  45. * Accepts options as a second argument:
  46. *
  47. * - commentDescriptions:
  48. * Provide true to use preceding comments as the description.
  49. *
  50. */
  51. export function printSchema(schema: GraphQLSchema, options?: Options): string {
  52. return printFilteredSchema(
  53. schema,
  54. (n) => !isSpecifiedDirective(n),
  55. isDefinedType,
  56. options,
  57. );
  58. }
  59. export function printIntrospectionSchema(
  60. schema: GraphQLSchema,
  61. options?: Options,
  62. ): string {
  63. return printFilteredSchema(
  64. schema,
  65. isSpecifiedDirective,
  66. isIntrospectionType,
  67. options,
  68. );
  69. }
  70. function isDefinedType(type: GraphQLNamedType): boolean {
  71. return !isSpecifiedScalarType(type) && !isIntrospectionType(type);
  72. }
  73. function printFilteredSchema(
  74. schema: GraphQLSchema,
  75. directiveFilter: (type: GraphQLDirective) => boolean,
  76. typeFilter: (type: GraphQLNamedType) => boolean,
  77. options,
  78. ): string {
  79. const directives = schema.getDirectives().filter(directiveFilter);
  80. const types = objectValues(schema.getTypeMap()).filter(typeFilter);
  81. return (
  82. [printSchemaDefinition(schema)]
  83. .concat(
  84. directives.map((directive) => printDirective(directive, options)),
  85. types.map((type) => printType(type, options)),
  86. )
  87. .filter(Boolean)
  88. .join('\n\n') + '\n'
  89. );
  90. }
  91. function printSchemaDefinition(schema: GraphQLSchema): ?string {
  92. if (schema.description == null && isSchemaOfCommonNames(schema)) {
  93. return;
  94. }
  95. const operationTypes = [];
  96. const queryType = schema.getQueryType();
  97. if (queryType) {
  98. operationTypes.push(` query: ${queryType.name}`);
  99. }
  100. const mutationType = schema.getMutationType();
  101. if (mutationType) {
  102. operationTypes.push(` mutation: ${mutationType.name}`);
  103. }
  104. const subscriptionType = schema.getSubscriptionType();
  105. if (subscriptionType) {
  106. operationTypes.push(` subscription: ${subscriptionType.name}`);
  107. }
  108. return (
  109. printDescription({}, schema) + `schema {\n${operationTypes.join('\n')}\n}`
  110. );
  111. }
  112. /**
  113. * GraphQL schema define root types for each type of operation. These types are
  114. * the same as any other type and can be named in any manner, however there is
  115. * a common naming convention:
  116. *
  117. * schema {
  118. * query: Query
  119. * mutation: Mutation
  120. * }
  121. *
  122. * When using this naming convention, the schema description can be omitted.
  123. */
  124. function isSchemaOfCommonNames(schema: GraphQLSchema): boolean {
  125. const queryType = schema.getQueryType();
  126. if (queryType && queryType.name !== 'Query') {
  127. return false;
  128. }
  129. const mutationType = schema.getMutationType();
  130. if (mutationType && mutationType.name !== 'Mutation') {
  131. return false;
  132. }
  133. const subscriptionType = schema.getSubscriptionType();
  134. if (subscriptionType && subscriptionType.name !== 'Subscription') {
  135. return false;
  136. }
  137. return true;
  138. }
  139. export function printType(type: GraphQLNamedType, options?: Options): string {
  140. if (isScalarType(type)) {
  141. return printScalar(type, options);
  142. }
  143. if (isObjectType(type)) {
  144. return printObject(type, options);
  145. }
  146. if (isInterfaceType(type)) {
  147. return printInterface(type, options);
  148. }
  149. if (isUnionType(type)) {
  150. return printUnion(type, options);
  151. }
  152. if (isEnumType(type)) {
  153. return printEnum(type, options);
  154. }
  155. // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')
  156. if (isInputObjectType(type)) {
  157. return printInputObject(type, options);
  158. }
  159. // istanbul ignore next (Not reachable. All possible types have been considered)
  160. invariant(false, 'Unexpected type: ' + inspect((type: empty)));
  161. }
  162. function printScalar(type: GraphQLScalarType, options): string {
  163. return (
  164. printDescription(options, type) +
  165. `scalar ${type.name}` +
  166. printSpecifiedByUrl(type)
  167. );
  168. }
  169. function printImplementedInterfaces(
  170. type: GraphQLObjectType | GraphQLInterfaceType,
  171. ): string {
  172. const interfaces = type.getInterfaces();
  173. return interfaces.length
  174. ? ' implements ' + interfaces.map((i) => i.name).join(' & ')
  175. : '';
  176. }
  177. function printObject(type: GraphQLObjectType, options): string {
  178. return (
  179. printDescription(options, type) +
  180. `type ${type.name}` +
  181. printImplementedInterfaces(type) +
  182. printFields(options, type)
  183. );
  184. }
  185. function printInterface(type: GraphQLInterfaceType, options): string {
  186. return (
  187. printDescription(options, type) +
  188. `interface ${type.name}` +
  189. printImplementedInterfaces(type) +
  190. printFields(options, type)
  191. );
  192. }
  193. function printUnion(type: GraphQLUnionType, options): string {
  194. const types = type.getTypes();
  195. const possibleTypes = types.length ? ' = ' + types.join(' | ') : '';
  196. return printDescription(options, type) + 'union ' + type.name + possibleTypes;
  197. }
  198. function printEnum(type: GraphQLEnumType, options): string {
  199. const values = type
  200. .getValues()
  201. .map(
  202. (value, i) =>
  203. printDescription(options, value, ' ', !i) +
  204. ' ' +
  205. value.name +
  206. printDeprecated(value),
  207. );
  208. return (
  209. printDescription(options, type) + `enum ${type.name}` + printBlock(values)
  210. );
  211. }
  212. function printInputObject(type: GraphQLInputObjectType, options): string {
  213. const fields = objectValues(type.getFields()).map(
  214. (f, i) =>
  215. printDescription(options, f, ' ', !i) + ' ' + printInputValue(f),
  216. );
  217. return (
  218. printDescription(options, type) + `input ${type.name}` + printBlock(fields)
  219. );
  220. }
  221. function printFields(options, type) {
  222. const fields = objectValues(type.getFields()).map(
  223. (f, i) =>
  224. printDescription(options, f, ' ', !i) +
  225. ' ' +
  226. f.name +
  227. printArgs(options, f.args, ' ') +
  228. ': ' +
  229. String(f.type) +
  230. printDeprecated(f),
  231. );
  232. return printBlock(fields);
  233. }
  234. function printBlock(items) {
  235. return items.length !== 0 ? ' {\n' + items.join('\n') + '\n}' : '';
  236. }
  237. function printArgs(options, args, indentation = '') {
  238. if (args.length === 0) {
  239. return '';
  240. }
  241. // If every arg does not have a description, print them on one line.
  242. if (args.every((arg) => !arg.description)) {
  243. return '(' + args.map(printInputValue).join(', ') + ')';
  244. }
  245. return (
  246. '(\n' +
  247. args
  248. .map(
  249. (arg, i) =>
  250. printDescription(options, arg, ' ' + indentation, !i) +
  251. ' ' +
  252. indentation +
  253. printInputValue(arg),
  254. )
  255. .join('\n') +
  256. '\n' +
  257. indentation +
  258. ')'
  259. );
  260. }
  261. function printInputValue(arg) {
  262. const defaultAST = astFromValue(arg.defaultValue, arg.type);
  263. let argDecl = arg.name + ': ' + String(arg.type);
  264. if (defaultAST) {
  265. argDecl += ` = ${print(defaultAST)}`;
  266. }
  267. return argDecl;
  268. }
  269. function printDirective(directive, options) {
  270. return (
  271. printDescription(options, directive) +
  272. 'directive @' +
  273. directive.name +
  274. printArgs(options, directive.args) +
  275. (directive.isRepeatable ? ' repeatable' : '') +
  276. ' on ' +
  277. directive.locations.join(' | ')
  278. );
  279. }
  280. function printDeprecated(fieldOrEnumVal) {
  281. if (!fieldOrEnumVal.isDeprecated) {
  282. return '';
  283. }
  284. const reason = fieldOrEnumVal.deprecationReason;
  285. const reasonAST = astFromValue(reason, GraphQLString);
  286. if (reasonAST && reason !== DEFAULT_DEPRECATION_REASON) {
  287. return ' @deprecated(reason: ' + print(reasonAST) + ')';
  288. }
  289. return ' @deprecated';
  290. }
  291. function printSpecifiedByUrl(scalar: GraphQLScalarType) {
  292. if (scalar.specifiedByUrl == null) {
  293. return '';
  294. }
  295. const url = scalar.specifiedByUrl;
  296. const urlAST = astFromValue(url, GraphQLString);
  297. invariant(
  298. urlAST,
  299. 'Unexpected null value returned from `astFromValue` for specifiedByUrl',
  300. );
  301. return ' @specifiedBy(url: ' + print(urlAST) + ')';
  302. }
  303. function printDescription(
  304. options,
  305. def,
  306. indentation = '',
  307. firstInBlock = true,
  308. ): string {
  309. const { description } = def;
  310. if (description == null) {
  311. return '';
  312. }
  313. if (options?.commentDescriptions === true) {
  314. return printDescriptionWithComments(description, indentation, firstInBlock);
  315. }
  316. const preferMultipleLines = description.length > 70;
  317. const blockString = printBlockString(description, '', preferMultipleLines);
  318. const prefix =
  319. indentation && !firstInBlock ? '\n' + indentation : indentation;
  320. return prefix + blockString.replace(/\n/g, '\n' + indentation) + '\n';
  321. }
  322. function printDescriptionWithComments(description, indentation, firstInBlock) {
  323. const prefix = indentation && !firstInBlock ? '\n' : '';
  324. const comment = description
  325. .split('\n')
  326. .map((line) => indentation + (line !== '' ? '# ' + line : '#'))
  327. .join('\n');
  328. return prefix + comment + '\n';
  329. }