buildClientSchema.mjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. import { devAssert } from '../jsutils/devAssert.mjs';
  2. import { inspect } from '../jsutils/inspect.mjs';
  3. import { isObjectLike } from '../jsutils/isObjectLike.mjs';
  4. import { keyValMap } from '../jsutils/keyValMap.mjs';
  5. import { parseValue } from '../language/parser.mjs';
  6. import {
  7. assertInterfaceType,
  8. assertNullableType,
  9. assertObjectType,
  10. GraphQLEnumType,
  11. GraphQLInputObjectType,
  12. GraphQLInterfaceType,
  13. GraphQLList,
  14. GraphQLNonNull,
  15. GraphQLObjectType,
  16. GraphQLScalarType,
  17. GraphQLUnionType,
  18. isInputType,
  19. isOutputType,
  20. } from '../type/definition.mjs';
  21. import { GraphQLDirective } from '../type/directives.mjs';
  22. import { introspectionTypes, TypeKind } from '../type/introspection.mjs';
  23. import { specifiedScalarTypes } from '../type/scalars.mjs';
  24. import { GraphQLSchema } from '../type/schema.mjs';
  25. import { valueFromAST } from './valueFromAST.mjs';
  26. /**
  27. * Build a GraphQLSchema for use by client tools.
  28. *
  29. * Given the result of a client running the introspection query, creates and
  30. * returns a GraphQLSchema instance which can be then used with all graphql-js
  31. * tools, but cannot be used to execute a query, as introspection does not
  32. * represent the "resolver", "parse" or "serialize" functions or any other
  33. * server-internal mechanisms.
  34. *
  35. * This function expects a complete introspection result. Don't forget to check
  36. * the "errors" field of a server response before calling this function.
  37. */
  38. export function buildClientSchema(introspection, options) {
  39. (isObjectLike(introspection) && isObjectLike(introspection.__schema)) ||
  40. devAssert(
  41. false,
  42. `Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: ${inspect(
  43. introspection,
  44. )}.`,
  45. ); // Get the schema from the introspection result.
  46. const schemaIntrospection = introspection.__schema; // Iterate through all types, getting the type definition for each.
  47. const typeMap = keyValMap(
  48. schemaIntrospection.types,
  49. (typeIntrospection) => typeIntrospection.name,
  50. (typeIntrospection) => buildType(typeIntrospection),
  51. ); // Include standard types only if they are used.
  52. for (const stdType of [...specifiedScalarTypes, ...introspectionTypes]) {
  53. if (typeMap[stdType.name]) {
  54. typeMap[stdType.name] = stdType;
  55. }
  56. } // Get the root Query, Mutation, and Subscription types.
  57. const queryType = schemaIntrospection.queryType
  58. ? getObjectType(schemaIntrospection.queryType)
  59. : null;
  60. const mutationType = schemaIntrospection.mutationType
  61. ? getObjectType(schemaIntrospection.mutationType)
  62. : null;
  63. const subscriptionType = schemaIntrospection.subscriptionType
  64. ? getObjectType(schemaIntrospection.subscriptionType)
  65. : null; // Get the directives supported by Introspection, assuming empty-set if
  66. // directives were not queried for.
  67. const directives = schemaIntrospection.directives
  68. ? schemaIntrospection.directives.map(buildDirective)
  69. : []; // Then produce and return a Schema with these types.
  70. return new GraphQLSchema({
  71. description: schemaIntrospection.description,
  72. query: queryType,
  73. mutation: mutationType,
  74. subscription: subscriptionType,
  75. types: Object.values(typeMap),
  76. directives,
  77. assumeValid:
  78. options === null || options === void 0 ? void 0 : options.assumeValid,
  79. }); // Given a type reference in introspection, return the GraphQLType instance.
  80. // preferring cached instances before building new instances.
  81. function getType(typeRef) {
  82. if (typeRef.kind === TypeKind.LIST) {
  83. const itemRef = typeRef.ofType;
  84. if (!itemRef) {
  85. throw new Error('Decorated type deeper than introspection query.');
  86. }
  87. return new GraphQLList(getType(itemRef));
  88. }
  89. if (typeRef.kind === TypeKind.NON_NULL) {
  90. const nullableRef = typeRef.ofType;
  91. if (!nullableRef) {
  92. throw new Error('Decorated type deeper than introspection query.');
  93. }
  94. const nullableType = getType(nullableRef);
  95. return new GraphQLNonNull(assertNullableType(nullableType));
  96. }
  97. return getNamedType(typeRef);
  98. }
  99. function getNamedType(typeRef) {
  100. const typeName = typeRef.name;
  101. if (!typeName) {
  102. throw new Error(`Unknown type reference: ${inspect(typeRef)}.`);
  103. }
  104. const type = typeMap[typeName];
  105. if (!type) {
  106. throw new Error(
  107. `Invalid or incomplete schema, unknown type: ${typeName}. Ensure that a full introspection query is used in order to build a client schema.`,
  108. );
  109. }
  110. return type;
  111. }
  112. function getObjectType(typeRef) {
  113. return assertObjectType(getNamedType(typeRef));
  114. }
  115. function getInterfaceType(typeRef) {
  116. return assertInterfaceType(getNamedType(typeRef));
  117. } // Given a type's introspection result, construct the correct
  118. // GraphQLType instance.
  119. function buildType(type) {
  120. // eslint-disable-next-line @typescript-eslint/prefer-optional-chain
  121. if (type != null && type.name != null && type.kind != null) {
  122. // FIXME: Properly type IntrospectionType, it's a breaking change so fix in v17
  123. // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check
  124. switch (type.kind) {
  125. case TypeKind.SCALAR:
  126. return buildScalarDef(type);
  127. case TypeKind.OBJECT:
  128. return buildObjectDef(type);
  129. case TypeKind.INTERFACE:
  130. return buildInterfaceDef(type);
  131. case TypeKind.UNION:
  132. return buildUnionDef(type);
  133. case TypeKind.ENUM:
  134. return buildEnumDef(type);
  135. case TypeKind.INPUT_OBJECT:
  136. return buildInputObjectDef(type);
  137. }
  138. }
  139. const typeStr = inspect(type);
  140. throw new Error(
  141. `Invalid or incomplete introspection result. Ensure that a full introspection query is used in order to build a client schema: ${typeStr}.`,
  142. );
  143. }
  144. function buildScalarDef(scalarIntrospection) {
  145. return new GraphQLScalarType({
  146. name: scalarIntrospection.name,
  147. description: scalarIntrospection.description,
  148. specifiedByURL: scalarIntrospection.specifiedByURL,
  149. });
  150. }
  151. function buildImplementationsList(implementingIntrospection) {
  152. // TODO: Temporary workaround until GraphQL ecosystem will fully support
  153. // 'interfaces' on interface types.
  154. if (
  155. implementingIntrospection.interfaces === null &&
  156. implementingIntrospection.kind === TypeKind.INTERFACE
  157. ) {
  158. return [];
  159. }
  160. if (!implementingIntrospection.interfaces) {
  161. const implementingIntrospectionStr = inspect(implementingIntrospection);
  162. throw new Error(
  163. `Introspection result missing interfaces: ${implementingIntrospectionStr}.`,
  164. );
  165. }
  166. return implementingIntrospection.interfaces.map(getInterfaceType);
  167. }
  168. function buildObjectDef(objectIntrospection) {
  169. return new GraphQLObjectType({
  170. name: objectIntrospection.name,
  171. description: objectIntrospection.description,
  172. interfaces: () => buildImplementationsList(objectIntrospection),
  173. fields: () => buildFieldDefMap(objectIntrospection),
  174. });
  175. }
  176. function buildInterfaceDef(interfaceIntrospection) {
  177. return new GraphQLInterfaceType({
  178. name: interfaceIntrospection.name,
  179. description: interfaceIntrospection.description,
  180. interfaces: () => buildImplementationsList(interfaceIntrospection),
  181. fields: () => buildFieldDefMap(interfaceIntrospection),
  182. });
  183. }
  184. function buildUnionDef(unionIntrospection) {
  185. if (!unionIntrospection.possibleTypes) {
  186. const unionIntrospectionStr = inspect(unionIntrospection);
  187. throw new Error(
  188. `Introspection result missing possibleTypes: ${unionIntrospectionStr}.`,
  189. );
  190. }
  191. return new GraphQLUnionType({
  192. name: unionIntrospection.name,
  193. description: unionIntrospection.description,
  194. types: () => unionIntrospection.possibleTypes.map(getObjectType),
  195. });
  196. }
  197. function buildEnumDef(enumIntrospection) {
  198. if (!enumIntrospection.enumValues) {
  199. const enumIntrospectionStr = inspect(enumIntrospection);
  200. throw new Error(
  201. `Introspection result missing enumValues: ${enumIntrospectionStr}.`,
  202. );
  203. }
  204. return new GraphQLEnumType({
  205. name: enumIntrospection.name,
  206. description: enumIntrospection.description,
  207. values: keyValMap(
  208. enumIntrospection.enumValues,
  209. (valueIntrospection) => valueIntrospection.name,
  210. (valueIntrospection) => ({
  211. description: valueIntrospection.description,
  212. deprecationReason: valueIntrospection.deprecationReason,
  213. }),
  214. ),
  215. });
  216. }
  217. function buildInputObjectDef(inputObjectIntrospection) {
  218. if (!inputObjectIntrospection.inputFields) {
  219. const inputObjectIntrospectionStr = inspect(inputObjectIntrospection);
  220. throw new Error(
  221. `Introspection result missing inputFields: ${inputObjectIntrospectionStr}.`,
  222. );
  223. }
  224. return new GraphQLInputObjectType({
  225. name: inputObjectIntrospection.name,
  226. description: inputObjectIntrospection.description,
  227. fields: () => buildInputValueDefMap(inputObjectIntrospection.inputFields),
  228. });
  229. }
  230. function buildFieldDefMap(typeIntrospection) {
  231. if (!typeIntrospection.fields) {
  232. throw new Error(
  233. `Introspection result missing fields: ${inspect(typeIntrospection)}.`,
  234. );
  235. }
  236. return keyValMap(
  237. typeIntrospection.fields,
  238. (fieldIntrospection) => fieldIntrospection.name,
  239. buildField,
  240. );
  241. }
  242. function buildField(fieldIntrospection) {
  243. const type = getType(fieldIntrospection.type);
  244. if (!isOutputType(type)) {
  245. const typeStr = inspect(type);
  246. throw new Error(
  247. `Introspection must provide output type for fields, but received: ${typeStr}.`,
  248. );
  249. }
  250. if (!fieldIntrospection.args) {
  251. const fieldIntrospectionStr = inspect(fieldIntrospection);
  252. throw new Error(
  253. `Introspection result missing field args: ${fieldIntrospectionStr}.`,
  254. );
  255. }
  256. return {
  257. description: fieldIntrospection.description,
  258. deprecationReason: fieldIntrospection.deprecationReason,
  259. type,
  260. args: buildInputValueDefMap(fieldIntrospection.args),
  261. };
  262. }
  263. function buildInputValueDefMap(inputValueIntrospections) {
  264. return keyValMap(
  265. inputValueIntrospections,
  266. (inputValue) => inputValue.name,
  267. buildInputValue,
  268. );
  269. }
  270. function buildInputValue(inputValueIntrospection) {
  271. const type = getType(inputValueIntrospection.type);
  272. if (!isInputType(type)) {
  273. const typeStr = inspect(type);
  274. throw new Error(
  275. `Introspection must provide input type for arguments, but received: ${typeStr}.`,
  276. );
  277. }
  278. const defaultValue =
  279. inputValueIntrospection.defaultValue != null
  280. ? valueFromAST(parseValue(inputValueIntrospection.defaultValue), type)
  281. : undefined;
  282. return {
  283. description: inputValueIntrospection.description,
  284. type,
  285. defaultValue,
  286. deprecationReason: inputValueIntrospection.deprecationReason,
  287. };
  288. }
  289. function buildDirective(directiveIntrospection) {
  290. if (!directiveIntrospection.args) {
  291. const directiveIntrospectionStr = inspect(directiveIntrospection);
  292. throw new Error(
  293. `Introspection result missing directive args: ${directiveIntrospectionStr}.`,
  294. );
  295. }
  296. if (!directiveIntrospection.locations) {
  297. const directiveIntrospectionStr = inspect(directiveIntrospection);
  298. throw new Error(
  299. `Introspection result missing directive locations: ${directiveIntrospectionStr}.`,
  300. );
  301. }
  302. return new GraphQLDirective({
  303. name: directiveIntrospection.name,
  304. description: directiveIntrospection.description,
  305. isRepeatable: directiveIntrospection.isRepeatable,
  306. locations: directiveIntrospection.locations.slice(),
  307. args: buildInputValueDefMap(directiveIntrospection.args),
  308. });
  309. }
  310. }