diff --git a/website/css/globals.css b/website/css/globals.css index e37406e328..58e95138a6 100644 --- a/website/css/globals.css +++ b/website/css/globals.css @@ -118,6 +118,14 @@ div[id^='headlessui-menu-items'] { word-break: keep-all; } +.api-category-toc a.api-deprecated-link { + text-decoration-line: underline line-through; +} + +.api-category-toc span[aria-hidden='true'] { + margin: 0 0.35rem; +} + .api-item-divider { margin: 2rem 0; border: 0; @@ -155,6 +163,24 @@ div[id^='headlessui-menu-items'] { white-space: nowrap; } +.api-tag::before { + content: 'Deprecated'; +} + +.nextra-toc .api-deprecated-title { + text-decoration: line-through; + text-decoration-thickness: from-font; +} + +.nextra-toc .api-tag { + display: none; +} + +.api-docs-route .nextra-sidebar-container a[href='/api-v16/subscription/'] { + text-decoration-line: line-through; + text-decoration-thickness: from-font; +} + .api-docs-route table { border-collapse: collapse; display: table; diff --git a/website/generate-api.js b/website/generate-api.js index 6bcd5d2b50..f65bd9ae4f 100644 --- a/website/generate-api.js +++ b/website/generate-api.js @@ -83,7 +83,7 @@ const typeNodeKeywordNames = new Map([ const apiCodeComponents = ['ApiSignature', 'ApiType']; const deprecatedTagMarkup = - 'Deprecated'; + ''; const renderContext = emptyRenderContext(); let sourceContext = emptySourceContext(); @@ -288,6 +288,7 @@ function emptyRenderContext() { return { docsBasePath: '', docsIndex: emptyDocsIndex(), + reflectionsById: new Map(), }; } @@ -566,25 +567,31 @@ function summary(node) { } function directCategory(node) { + const declaration = documentationNode(node); return ( tagText(node.comment, '@category') || tagText(node.signatures?.[0]?.comment, '@category') || + (declaration === node + ? '' + : tagText(declaration.comment, '@category') || + tagText(declaration.signatures?.[0]?.comment, '@category')) || null ); } function resolveItemCategory(node, siblings = []) { + const declaration = documentationNode(node); const ownCategory = directCategory(node); if (ownCategory != null && ownCategory !== '') { return ownCategory; } - if (isEnumNamespace(node)) { - return commonCategory(enumLikeMembers(node).map(directCategory)); + if (isEnumNamespace(declaration)) { + return commonCategory(enumLikeMembers(declaration).map(directCategory)); } - for (const sibling of siblings) { - if (sibling === node || sibling.name !== node.name) { + for (const sibling of documentationSiblings(siblings)) { + if (sibling === declaration || sibling.name !== declaration.name) { continue; } const siblingCategory = directCategory(sibling); @@ -665,18 +672,33 @@ function heading(level, label) { } function isDeprecated(node) { - return hasCommentTag(node?.comment, '@deprecated'); + const declaration = documentationNode(node); + return ( + hasCommentTag(node?.comment, '@deprecated') || + (declaration !== node && hasCommentTag(declaration?.comment, '@deprecated')) + ); } function deprecatedTag(node) { return isDeprecated(node) ? ` ${deprecatedTagMarkup}` : ''; } -function callableDeprecatedTag(node, signatures) { - return isDeprecated(node) || - (signatures.length === 1 && isDeprecated(signatures[0])) - ? ` ${deprecatedTagMarkup}` - : ''; +function isCallableDeprecated(node, signatures) { + const declaration = documentationNode(node); + const declarationSignatures = declaration.signatures ?? signatures; + return ( + isDeprecated(node) || + (declarationSignatures.length === 1 && + isDeprecated(declarationSignatures[0])) + ); +} + +function deprecatedHeadingLabel(label, deprecated) { + return deprecated + ? `${jsxText( + label, + )}${deprecatedTagMarkup}` + : label; } function code(value) { @@ -790,7 +812,10 @@ function tableCell(value) { if (isApiCodeComponentMarkup(cell)) { return cell; } - return mapInlineCodeSpans(cell, tableText, tableCode); + return cell + .split(deprecatedTagMarkup) + .map((part) => mapInlineCodeSpans(part, tableText, tableCode)) + .join(deprecatedTagMarkup); } function isApiCodeComponentMarkup(value) { @@ -862,6 +887,38 @@ function targetId(type) { : null; } +function isReflectionReference(node) { + return ( + node?.kind === ReflectionKind.Reference && node.variant === 'reference' + ); +} + +function documentationNode(node) { + let current = node; + const seen = new Set(); + + while (isReflectionReference(current)) { + const target = targetId(current); + if (target == null || seen.has(target)) { + break; + } + + const next = renderContext.reflectionsById.get(target); + if (next == null) { + break; + } + + seen.add(target); + current = next; + } + + return current; +} + +function documentationSiblings(siblings) { + return siblings.map(documentationNode); +} + function rawTypeName(type) { return typeName(type, { keepDefaultTypeArguments: true }); } @@ -2126,25 +2183,28 @@ function renderTypeAliasDeclaration(node, options = {}) { } function declarationKind(node, siblings = []) { - if (isEnumLikeDeclaration(node, siblings)) { + const declaration = documentationNode(node); + const declarationSiblings = documentationSiblings(siblings); + if (isEnumLikeDeclaration(declaration, declarationSiblings)) { return 'Enumerations'; } - if (node.kind === ReflectionKind.Class) { + if (declaration.kind === ReflectionKind.Class) { return 'Classes'; } - if (node.kind === ReflectionKind.Function) { + if (declaration.kind === ReflectionKind.Function) { return 'Functions'; } - if (node.kind === ReflectionKind.Variable) { + if (declaration.kind === ReflectionKind.Variable) { return 'Constants'; } - if (node.kind === ReflectionKind.Enum) { + if (declaration.kind === ReflectionKind.Enum) { return 'Enumerations'; } if ( - node.kind === ReflectionKind.TypeAlias || - node.kind === ReflectionKind.Interface || - (node.kind === ReflectionKind.Reference && node.variant === 'declaration') + declaration.kind === ReflectionKind.TypeAlias || + declaration.kind === ReflectionKind.Interface || + (declaration.kind === ReflectionKind.Reference && + declaration.variant === 'declaration') ) { return 'Types'; } @@ -2152,25 +2212,34 @@ function declarationKind(node, siblings = []) { } function isEnumLikeDeclaration(node, siblings = []) { - return isEnumNamespace(node) || isEnumLikeConstObject(node, siblings); + const declaration = documentationNode(node); + const declarationSiblings = documentationSiblings(siblings); + return ( + isEnumNamespace(declaration) || + isEnumLikeConstObject(declaration, declarationSiblings) + ); } function isEnumLikeConstObject(node, siblings = []) { + const declaration = documentationNode(node); + const declarationSiblings = documentationSiblings(siblings); return ( - node.kind === ReflectionKind.Variable && - hasMatchingTypeAlias(node, siblings) && - enumLikeMembers(node).length > 0 + declaration.kind === ReflectionKind.Variable && + hasMatchingTypeAlias(declaration, declarationSiblings) && + enumLikeMembers(declaration).length > 0 ); } function isEnumLikeTypeAlias(node, siblings = []) { + const declaration = documentationNode(node); + const declarationSiblings = documentationSiblings(siblings); return ( - node.kind === ReflectionKind.TypeAlias && - siblings.some( + declaration.kind === ReflectionKind.TypeAlias && + declarationSiblings.some( (sibling) => - sibling !== node && - sibling.name === node.name && - isEnumLikeConstObject(sibling, siblings), + sibling !== declaration && + sibling.name === declaration.name && + isEnumLikeConstObject(sibling, declarationSiblings), ) ); } @@ -2209,22 +2278,30 @@ function enumLikeMembers(node) { return visibleChildren(node.type?.declaration); } -function visibleChildren(node) { +function visibleChildren(node, options = {}) { if (node == null) { return []; } + if (options.includeReferences) { + return (node.children ?? []).filter((child) => + isVisibleChild(child, options), + ); + } + let children = visibleChildrenCache.get(node); if (children == null) { - children = (node.children ?? []).filter(isVisibleChild); + children = (node.children ?? []).filter((child) => + isVisibleChild(child, options), + ); visibleChildrenCache.set(node, children); } return children; } -function isVisibleChild(child) { +function isVisibleChild(child, options = {}) { return ( - child.variant !== 'reference' && + (options.includeReferences || !isReflectionReference(child)) && child.kind !== ReflectionKind.IndexSignature && !child.flags?.isExternal && !child.flags?.isInherited && @@ -2273,7 +2350,9 @@ function renderFields(parent, level, options = {}) { } const defaultValue = defaultText(child, parent, options); rows.push([ - `${htmlText(child.name)}${child.flags?.isOptional ? '?' : ''}`, + `${htmlText(child.name)}${ + child.flags?.isOptional ? '?' : '' + }${deprecatedTag(child)}`, renderApiType(child.type, options), defaultValue, summary(child), @@ -2299,7 +2378,9 @@ function renderParams(signature, options = {}) { for (const param of signature.parameters ?? []) { const defaultValue = defaultText(param, signature, options); rows.push([ - `${htmlText(param.name)}${param.flags?.isOptional ? '?' : ''}`, + `${htmlText(param.name)}${ + param.flags?.isOptional ? '?' : '' + }${deprecatedTag(param)}`, renderApiType(param.type, options), defaultValue, summary(param), @@ -2374,7 +2455,7 @@ function renderTypeParameters(node, options = {}) { } const rows = typeParameters.map((param) => [ - param.name, + `${param.name}${deprecatedTag(param)}`, param.type == null ? '' : renderApiType(param.type, options), param.default == null ? '' : renderApiType(param.default, options), summary(param), @@ -2425,7 +2506,13 @@ function renderCallable( const signatures = node.signatures ?? [node]; const headingLabel = label.endsWith(')') ? label : `${label}()`; const lines = [ - heading(level, `${headingLabel}${callableDeprecatedTag(node, signatures)}`), + heading( + level, + deprecatedHeadingLabel( + headingLabel, + isCallableDeprecated(node, signatures), + ), + ), ]; for (const [index, signature] of signatures.entries()) { @@ -2454,6 +2541,15 @@ function renderCallable( } function renderDeclaration(node, level = 3, siblings = []) { + const declaration = documentationNode(node); + if (declaration !== node) { + return renderDeclaration( + declaration, + level, + documentationSiblings(siblings), + ); + } + const lines = []; const options = sourceOptions(node); const title = @@ -2463,7 +2559,7 @@ function renderDeclaration(node, level = 3, siblings = []) { return renderCallable(node, level, title, options); } - lines.push(heading(level, `${title}${deprecatedTag(node)}`)); + lines.push(heading(level, deprecatedHeadingLabel(title, isDeprecated(node)))); const comment = renderComment(node); const label = typeLabel(node, siblings); @@ -2505,7 +2601,7 @@ function renderDeclaration(node, level = 3, siblings = []) { if (node.kind === ReflectionKind.Enum) { lines.push(...examples); const rows = visibleChildren(node).map((child) => [ - code(child.name), + `${code(child.name)}${deprecatedTag(child)}`, code(typeName(child.type, options)), summary(child), ]); @@ -2526,7 +2622,7 @@ function renderDeclaration(node, level = 3, siblings = []) { for (const signature of constructor.signatures ?? []) { lines.push( ...headingSubsection( - `Constructor${deprecatedTag(signature)}`, + deprecatedHeadingLabel('Constructor', isDeprecated(signature)), level + 1, ), ); @@ -2566,7 +2662,7 @@ function enumLikeNote(node) { function renderEnumMembers(node, options = {}) { const rows = enumLikeMembers(node).map((child) => [ - code(child.name), + `${code(child.name)}${deprecatedTag(child)}`, code(typeName(child.type, options)), summary(child), ]); @@ -2599,18 +2695,21 @@ function sourceFileName(node) { } function typeLabel(node, siblings = []) { + const declaration = documentationNode(node); + const declarationSiblings = documentationSiblings(siblings); if ( - node.kind === ReflectionKind.Enum || - isEnumLikeDeclaration(node, siblings) + declaration.kind === ReflectionKind.Enum || + isEnumLikeDeclaration(declaration, declarationSiblings) ) { return 'Enumeration'; } - if (node.kind === ReflectionKind.Interface) { + if (declaration.kind === ReflectionKind.Interface) { return 'Interface'; } if ( - node.kind === ReflectionKind.TypeAlias || - (node.kind === ReflectionKind.Reference && node.variant === 'declaration') + declaration.kind === ReflectionKind.TypeAlias || + (declaration.kind === ReflectionKind.Reference && + declaration.variant === 'declaration') ) { return 'Type alias'; } @@ -2626,7 +2725,9 @@ function moduleTitle(name) { } function moduleItems(module, name) { - return visibleChildren(module).filter( + return visibleChildren(module, { + includeReferences: name !== 'graphql', + }).filter( (item) => name !== 'graphql' || sourceContext.rootExportNames.has(item.name), ); @@ -2679,6 +2780,27 @@ function moduleDocs(module) { }; } +function createReflectionIndex(doc) { + const reflectionsById = new Map(); + collectReflection(reflectionsById, doc); + return reflectionsById; +} + +function collectReflection(reflectionsById, node) { + if (node == null) { + return; + } + if (typeof node.id === 'number') { + reflectionsById.set(node.id, node); + } + for (const child of node.children ?? []) { + collectReflection(reflectionsById, child); + } + for (const signature of node.signatures ?? []) { + collectReflection(reflectionsById, signature); + } +} + function createDocsIndex(modules) { const index = emptyDocsIndex(); @@ -2686,12 +2808,18 @@ function createDocsIndex(modules) { addSymbolDoc(index, docs.name, { page: docs.name }); for (const child of docs.items) { const childDoc = { page: docs.name, anchor: slug(child.name) }; + const declaration = documentationNode(child); index.docsById.set(child.id, childDoc); addSymbolDoc(index, child.name, childDoc); index.typeParameterDefaultsById.set( child.id, - (child.typeParameters ?? []).map((param) => param.default ?? null), + (declaration.typeParameters ?? []).map( + (param) => param.default ?? null, + ), ); + if (isReflectionReference(child)) { + continue; + } for (const member of visibleChildren(child)) { const memberDoc = { page: docs.name, anchor: slug(member.name) }; index.docsById.set(member.id, memberDoc); @@ -2779,9 +2907,17 @@ function renderItemToc(groups, page) { } function tocLink(item, page) { + const declaration = documentationNode(item); const label = - item.kind === ReflectionKind.Function ? `${item.name}()` : item.name; - return `${jsxText(label)}`; } @@ -2853,7 +2989,11 @@ function categorySection(name, items, moduleName) { } function renderModulePage(docs) { - const content = [summary(docs.module)]; + const content = []; + if (isDeprecatedModule(docs)) { + content.push(heading(1, deprecatedHeadingLabel(docs.title, true))); + } + content.push(summary(docs.module)); if (docs.categories.length === 1) { content.push( renderItems(docs.byCategory.get(docs.categories[0]), docs.name).trimEnd(), @@ -2869,6 +3009,14 @@ function renderModulePage(docs) { return content.filter(Boolean).join('\n\n') + '\n'; } +function isDeprecatedModule(docs) { + return ( + isDeprecated(docs.module) || + (docs.name === 'subscription' && + /\bdeprecated\b/i.test(summary(docs.module))) + ); +} + function addModuleMeta(meta, docs) { const entry = [docs.name, docs.title]; if (docs.name === 'graphql') { @@ -2906,16 +3054,20 @@ function writeCategoryMeta(docs) { } function buildApiReference(doc) { + const reflectionsById = createReflectionIndex(doc); + renderContext.reflectionsById = reflectionsById; const modules = (doc.children ?? []).map(moduleDocs); return { index: createDocsIndex(modules), modules, + reflectionsById, }; } function writeApiReference(reference) { renderContext.docsBasePath = generation.docsBasePath; renderContext.docsIndex = reference.index; + renderContext.reflectionsById = reference.reflectionsById; rmSync(generation.outputDir, { recursive: true, force: true }); mkdirSync(generation.outputDir, { recursive: true }); @@ -2952,6 +3104,23 @@ function addCategory(comment, category) { ); } +function leadingJSDocRange(content, node) { + const index = node.getStart(); + const before = content.slice(0, index); + const start = before.lastIndexOf('/**'); + const end = start === -1 ? -1 : before.indexOf('*/', start); + const jsdocEnd = end === -1 ? -1 : end + 2; + + if ( + start === -1 || + jsdocEnd < start || + !isLeadingLineCommentTrivia(before.slice(jsdocEnd)) + ) { + return null; + } + return { start, end: jsdocEnd }; +} + function isLeadingLineCommentTrivia(value) { return value.replace(/\/\/[^\n\r]*(?:\r?\n|$)/g, '').trim() === ''; } @@ -3053,6 +3222,78 @@ function inheritFileCategories(dir) { }); } +function exposePublicOverloadSignatures(dir) { + // TypeDoc applies @internal on an overload implementation to the whole + // function reflection. Keep public overload signatures visible, but remove + // the implementation's own JSDoc from the generated snapshot. + walkFiles(dir, (path) => { + if (!path.endsWith('.ts')) { + return; + } + + let content = readFileSync(path, 'utf8'); + const ranges = publicOverloadImplementationJSDocRanges( + sourceFile(path, content), + content, + ); + for (let i = ranges.length - 1; i >= 0; i--) { + const range = ranges[i]; + content = + content.slice(0, range.start) + + content.slice(range.end).replace(/^\r?\n/, ''); + } + + if (ranges.length > 0) { + writeFileSync(path, content); + } + }); +} + +function publicOverloadImplementationJSDocRanges(ast, content) { + const localExports = localExportNames(ast); + const declarationsByName = new Map(); + + for (const statement of ast.statements) { + if ( + !ts.isFunctionDeclaration(statement) || + statement.name == null || + (!isExported(statement) && !localExports.has(statement.name.text)) + ) { + continue; + } + + const declarations = declarationsByName.get(statement.name.text) ?? []; + declarations.push(statement); + declarationsByName.set(statement.name.text, declarations); + } + + const ranges = []; + for (const declarations of declarationsByName.values()) { + const hasPublicOverload = declarations.some( + (declaration) => + declaration.body == null && + !hasJSDocTag(declaration, 'internal') && + !hasJSDocTag(declaration, 'private'), + ); + if (!hasPublicOverload) { + continue; + } + + for (const declaration of declarations) { + if (declaration.body == null || !hasJSDocTag(declaration, 'internal')) { + continue; + } + + const range = leadingJSDocRange(content, declaration); + if (range != null) { + ranges.push(range); + } + } + } + + return ranges; +} + function prepareSourceSnapshot() { // Snapshot the source before running TypeDoc so generation-only compatibility // fixes never mutate the working tree. @@ -3069,6 +3310,7 @@ function copySourceSnapshot(sourceDir, tmpSourceDir) { }); stripCoverageIgnoreComments(join(tmpSourceDir, 'src')); inheritFileCategories(join(tmpSourceDir, 'src')); + exposePublicOverloadSignatures(join(tmpSourceDir, 'src')); } function stripCoverageIgnoreComments(dir) { diff --git a/website/pages/api-v16/error.mdx b/website/pages/api-v16/error.mdx index aed9997068..81e367b9ca 100644 --- a/website/pages/api-v16/error.mdx +++ b/website/pages/api-v16/error.mdx @@ -11,9 +11,9 @@ These exports are also available from the root `graphql` package.

Functions:
- printError() + printError() - formatError() + formatError() locatedError() @@ -80,7 +80,7 @@ This positional-arguments constructor overload is deprecated. Use the


-#### Constructor Deprecated +#### Constructor Creates a GraphQLError instance using the legacy positional constructor. This deprecated overload will be removed in v17. Prefer the @@ -296,7 +296,7 @@ error.toJSON(); // => { message: 'Resolver failed.', path: ['viewer', 'name'], e ## Functions -### printError() Deprecated +### printError() Prints a GraphQLError to a string, representing useful location information about the error's position in the source. This deprecated helper is retained @@ -361,7 +361,7 @@ message; // => 'Example error'
-### formatError() Deprecated +### formatError() Given a GraphQLError, format it according to the rules described by the Response Format, Errors section of the GraphQL Specification. This deprecated diff --git a/website/pages/api-v16/execution.mdx b/website/pages/api-v16/execution.mdx index 209075915c..30453705f5 100644 --- a/website/pages/api-v16/execution.mdx +++ b/website/pages/api-v16/execution.mdx @@ -589,6 +589,8 @@ of calling that function while passing along args and context value.

Functions:
subscribe() + + createSourceEventStream()

@@ -785,6 +787,234 @@ assert('errors' in result); result.errors[0].message; // => 'Schema is not configured to execute subscription operation.' ``` +
+ +#### createSourceEventStream() + +
+ +
Overload 1
+ +Implements the "CreateSourceEventStream" algorithm described in the +GraphQL specification, resolving the subscription source event stream. + +Returns a Promise that resolves to either an AsyncIterable (if successful) +or an ExecutionResult (error). The promise will be rejected if the schema or +other arguments to this function are invalid, or if the resolved event stream +is not an async iterable. + +If the client-provided arguments to this function do not result in a +compliant subscription, a GraphQL Response (ExecutionResult) with +descriptive errors and no data will be returned. + +If the source stream could not be created due to faulty subscription +resolver logic or underlying systems, the promise will resolve to a single +ExecutionResult containing `errors` and no `data`. + +If the operation succeeded, the promise resolves to the AsyncIterable for the +event stream returned by the resolver. + +A Source Event Stream represents a sequence of events, each of which triggers +a GraphQL execution for that event. + +This may be useful when hosting the stateful subscription service in a +different process or machine than the stateless GraphQL execution engine, +or otherwise separating these two steps. For more on this, see the +"Supporting Subscriptions at Scale" information in the GraphQL specification. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
argsThe arguments used to perform the operation.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The source event stream, or an execution result containing subscription errors.
+ +
+ +
Example
+ +```ts +import { parse } from 'graphql/language'; +import { buildSchema } from 'graphql/utilities'; +import { createSourceEventStream } from 'graphql/execution'; + +async function* greetings() { + yield { greeting: 'Hello' }; +} + +const schema = buildSchema(` + type Query { + noop: String + } + + type Subscription { + greeting: String + } +`); + +const stream = await createSourceEventStream({ + schema, + document: parse('subscription { greeting }'), + rootValue: { greeting: () => greetings() }, +}); + +Symbol.asyncIterator in stream; // => true +``` + +
+ +
Overload 2
+ +Creates the source event stream for a subscription operation using the legacy +positional argument overload. This deprecated overload will be removed in the +next major version; use the args object overload instead. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
schemaGraphQL schema to use.
documentThe parsed GraphQL document containing the subscription
+operation.
rootValue?Initial root value passed to the subscription resolver.
contextValue?Application context value passed to resolvers.
variableValues?Runtime variable values keyed by variable name.
operationName?Name of the subscription operation to execute when
+the document contains multiple operations.
subscribeFieldResolver?Resolver used for the root subscription
+field.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The source event stream, or an execution result containing
+subscription errors.
+ +
+ +
Example
+ +```ts +import { parse } from 'graphql/language'; +import { buildSchema } from 'graphql/utilities'; +import { createSourceEventStream } from 'graphql/execution'; + +async function* greetings() { + yield { greeting: 'Hello' }; +} + +const schema = buildSchema(` + type Query { + noop: String + } + + type Subscription { + greeting: String + } +`); +const document = parse('subscription { greeting }'); + +const stream = await createSourceEventStream(schema, document, { + greeting: () => greetings(), +}); + +Symbol.asyncIterator in stream; // => true +``` + ## Category: Values
diff --git a/website/pages/api-v16/language.mdx b/website/pages/api-v16/language.mdx index 342bfe023b..29b2097e43 100644 --- a/website/pages/api-v16/language.mdx +++ b/website/pages/api-v16/language.mdx @@ -1040,7 +1040,7 @@ token; // => { kind: '{', value: undefined, line: 1, column: 1 } Name node identifying this AST node. - variableDefinitions? + variableDefinitions? Deprecated variable definitions declared by this legacy fragment
definition. This legacy fragment variable syntax will be removed in v17.
@@ -2997,9 +2997,9 @@ complete experimental fragment-arguments feature.

Types:
- DirectiveLocationEnum + DirectiveLocationEnum - KindEnum + KindEnum

@@ -3431,7 +3431,7 @@ complete experimental fragment-arguments feature. ### Types -#### DirectiveLocationEnum Deprecated +#### DirectiveLocationEnum **Type alias.** Deprecated legacy alias for the enum type representing directive location values. This alias will be removed in v17. In v17, [`DirectiveLocation`](/api-v16/language#directivelocation) is @@ -3442,7 +3442,7 @@ corresponding TypeScript type.
-#### KindEnum Deprecated +#### KindEnum **Type alias.** Deprecated legacy alias for the enum type representing the possible kind values of AST nodes. This alias will be removed in v17. In v17, [`Kind`](/api-v16/language#kind) is @@ -3464,7 +3464,7 @@ corresponding TypeScript type.

Types:
- TokenKindEnum + TokenKindEnum

@@ -3778,7 +3778,7 @@ lexer emits. ### Types -#### TokenKindEnum Deprecated +#### TokenKindEnum **Type alias.** Deprecated legacy alias for the enum type representing token kind values. This alias will be removed in v17. In v17, [`TokenKind`](/api-v16/language#tokenkind) is exported as the @@ -4566,7 +4566,7 @@ CPU time and memory.
To prevent this you can set a maximum number of tokens allowed within a document. - allowLegacyFragmentVariables? + allowLegacyFragmentVariables? Deprecated option that allows legacy fragment variable definitions to be
parsed. This legacy fragment variable syntax will be removed in v17. Move
@@ -5418,11 +5418,13 @@ text; // => '{\n hero {\n name\n }\n}'

Functions:
+ visit() + visitInParallel() getEnterLeaveForKind() - getVisitFn() + getVisitFn()

Constants:
@@ -5434,12 +5436,340 @@ text; // => '{\n hero {\n name\n }\n}' ASTVisitFn - ASTVisitorKeyMap + ASTVisitorKeyMap

### Functions +#### visit() + +
+ +
Overload 1
+ +visit() will walk through an AST using a depth-first traversal, calling +the visitor's enter function at each node in the traversal, and calling the +leave function after visiting that node and all of its child nodes. + +By returning different values from the enter and leave functions, the +behavior of the visitor can be altered, including skipping over a sub-tree of +the AST (by returning false), editing the AST by returning a value or null +to remove the value, or to stop the whole traversal by returning BREAK. + +When using visit() to edit an AST, the original AST will not be modified, and +a new version of the AST with the changes applied will be returned from the +visit function. + +
+ +
Type Parameters
+ + + + + + + + + + + + + + + + + + +
NameConstraintDefaultDescription
NThe root AST node type returned when visiting without reducing.
+ +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDefaultDescription
rootThe AST node at which to start traversal.
visitorThe visitor or reducer functions to call while traversing.
visitorKeys?Optional map of child keys to visit for each AST node kind.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The original AST, an edited AST, or a reduced value depending on the visitor.
+ +
+ +
Example 1
+ +```ts +// Return values control traversal: undefined makes no change, false skips +// a subtree, BREAK stops traversal, null removes a node, and any other +// value replaces the current node. +import { Kind, parse, print, visit } from 'graphql/language'; + +const document = parse('{ hero { name } }'); +const editedAST = visit(document, { + Field: (node) => { + if (node.name.value === 'hero') { + return { + ...node, + name: { kind: Kind.NAME, value: 'human' }, + }; + } + }, +}); + +print(editedAST); // => '{\n human {\n name\n }\n}' +``` + +
+ +
Example 2
+ +```ts +// A named visitor function runs when entering nodes of that kind. +import { parse, visit } from 'graphql/language'; + +const document = parse('{ hero { name } }'); +const fieldNames = []; + +visit(document, { + Field: (node) => { + fieldNames.push(node.name.value); + }, +}); + +fieldNames; // => ['hero', 'name'] +``` + +
+ +
Example 3
+ +```ts +// A named visitor object can provide separate enter and leave handlers for +// nodes of that kind. +import { parse, visit } from 'graphql/language'; + +const document = parse('{ hero { name } }'); +const events = []; + +visit(document, { + Field: { + enter: (node) => { + events.push(`enter:${node.name.value}`); + }, + leave: (node) => { + events.push(`leave:${node.name.value}`); + }, + }, +}); + +events; // => ['enter:hero', 'enter:name', 'leave:name', 'leave:hero'] +``` + +
+ +
Example 4
+ +```ts +// Generic enter and leave handlers run for every node. +import { parse, visit } from 'graphql/language'; + +const document = parse('{ hero { name } }'); +let enterCount = 0; +let leaveCount = 0; + +visit(document, { + enter: (node) => { + enterCount += 1; + }, + leave: (node) => { + leaveCount += 1; + }, +}); + +enterCount; // => leaveCount +enterCount > 0; // => true +``` + +
+ +
Overload 2
+ +Traverses an AST with reducer callbacks and returns the reduced value. + +
+ +
Type Parameters
+ + + + + + + + + + + + + + + + + + +
NameConstraintDefaultDescription
RThe value produced by reducer visitor callbacks.
+ +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDefaultDescription
rootThe AST node where traversal starts.
visitorReducer callbacks to invoke during traversal.
visitorKeys?Optional mapping of child keys for each AST node kind.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The value produced by the reducer visitor.
+ +
+ +
Example
+ +```ts +// A reducer visitor returns values from leave handlers to build a reduced +// result instead of returning an edited AST. +import { parse, visit } from 'graphql/language'; + +const document = parse('{ hero { name } }'); +const printed = visit(document, { + Name: { + leave: (node) => { + return node.value; + }, + }, + Field: { + leave: (node) => { + return node.selectionSet == null + ? node.name + : `${node.name} { ${node.selectionSet} }`; + }, + }, + SelectionSet: { + leave: (node) => { + return node.selections.join(' '); + }, + }, + OperationDefinition: { + leave: (node) => { + return node.selectionSet; + }, + }, + Document: { + leave: (node) => { + return node.definitions.join('\n'); + }, + }, +}); + +printed; // => 'hero { name }' +``` + +
+ #### visitInParallel() Creates a new visitor instance which delegates to many visitors to run in @@ -5582,7 +5912,7 @@ handlers.leave; // => undefined
-#### getVisitFn() Deprecated +#### getVisitFn() Given a visitor instance, if it is leaving or not, and a node kind, return the function the visitor runtime should call. This deprecated compatibility @@ -5710,7 +6040,7 @@ A value that can be returned from a visitor function to stop traversal.
-#### ASTVisitorKeyMap Deprecated +#### ASTVisitorKeyMap **Type alias.** Deprecated visitor key map type retained for compatibility. Inline this mapped type at use sites because ASTVisitorKeyMap will be removed in v17. diff --git a/website/pages/api-v16/subscription.mdx b/website/pages/api-v16/subscription.mdx index fa8476ae76..69c068cb13 100644 --- a/website/pages/api-v16/subscription.mdx +++ b/website/pages/api-v16/subscription.mdx @@ -1,4 +1,6 @@ -import { ApiSignature } from '../../components/ApiCode'; +import { ApiSignature, ApiType } from '../../components/ApiCode'; + +# graphql/subscription NOTE: the `graphql/subscription` module has been deprecated with its exported functions integrated into the `graphql/execution` module, to @@ -11,15 +13,442 @@ module. In v17, the `graphql/subscription` module will be dropped entirely. These exports are also available from the root `graphql` package. +## Functions + +### subscribe() + +Implements the "Subscribe" algorithm described in the GraphQL specification. + +Returns a Promise that resolves to either an AsyncIterator (if successful) +or an ExecutionResult (error). The promise will be rejected if the schema or +other arguments to this function are invalid, or if the resolved event stream +is not an async iterable. + +If the client-provided arguments to this function do not result in a +compliant subscription, a GraphQL Response (ExecutionResult) with +descriptive errors and no data will be returned. + +If the source stream could not be created due to faulty subscription +resolver logic or underlying systems, the promise will resolve to a single +ExecutionResult containing `errors` and no `data`. + +If the operation succeeded, the promise resolves to an AsyncIterator, which +yields a stream of ExecutionResults representing the response stream. + +Each payload yielded by the source event stream is executed with the payload +as the root value. This maps the subscription source stream into the response +stream described by the GraphQL specification. + +Accepts an object with named arguments. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
argsThe arguments used to perform the operation.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
A source stream mapped to execution results, or an execution result
+containing subscription errors.
+ +
+ +
Example 1
+ +```ts +// Use a same-named rootValue function to provide the source event stream. +import assert from 'node:assert'; +import { parse } from 'graphql/language'; +import { buildSchema } from 'graphql/utilities'; +import { subscribe } from 'graphql/execution'; + +async function* greetings() { + yield { greeting: 'Hello' }; + yield { greeting: 'Bonjour' }; +} + +const schema = buildSchema(` + type Query { + noop: String + } + + type Subscription { + greeting: String + } +`); + +const result = await subscribe({ + schema, + document: parse('subscription { greeting }'), + rootValue: { greeting: () => greetings() }, +}); + +assert('next' in result); + +const firstPayload = await result.next(); +firstPayload.value; // => { data: { greeting: 'Hello' } } +``` + +
+ +
Example 2
+ +```ts +// This variant supplies events through a custom subscribeFieldResolver. +import assert from 'node:assert'; +import { parse } from 'graphql/language'; +import { buildSchema } from 'graphql/utilities'; +import { subscribe } from 'graphql/execution'; + +async function* defaultGreetings() { + yield { greeting: 'Hello' }; +} + +async function* frenchGreetings() { + yield { greeting: 'Bonjour' }; +} + +const schema = buildSchema(` + type Query { + noop: String + } + + type Subscription { + greeting(locale: String): String + } +`); + +const result = await subscribe({ + schema, + document: parse( + 'subscription Greeting($locale: String) { greeting(locale: $locale) }', + ), + rootValue: { + greeting: (args, contextValue) => { + const locale = args.locale ?? contextValue.defaultLocale; + return locale === 'fr' ? frenchGreetings() : defaultGreetings(); + }, + }, + contextValue: { defaultLocale: 'fr' }, + variableValues: { locale: 'fr' }, + operationName: 'Greeting', + subscribeFieldResolver: (rootValue, args, contextValue, info) => { + args.locale; // => 'fr' + return rootValue[info.fieldName](args, contextValue); + }, +}); + +assert('next' in result); + +const firstPayload = await result.next(); +firstPayload.value; // => { data: { greeting: 'Bonjour' } } +``` + +
+ +
Example 3
+ +```ts +// This variant shows the error result when the schema has no subscription root. +import assert from 'node:assert'; +import { parse } from 'graphql/language'; +import { buildSchema } from 'graphql/utilities'; +import { subscribe } from 'graphql/execution'; + +const schema = buildSchema(` + type Query { + noop: String + } +`); + +const result = await subscribe({ + schema, + document: parse('subscription { greeting }'), +}); + +assert('errors' in result); + +result.errors[0].message; // => 'Schema is not configured to execute subscription operation.' +``` + +
+ +### createSourceEventStream() + +
+ +
Overload 1
+ +Implements the "CreateSourceEventStream" algorithm described in the +GraphQL specification, resolving the subscription source event stream. + +Returns a Promise that resolves to either an AsyncIterable (if successful) +or an ExecutionResult (error). The promise will be rejected if the schema or +other arguments to this function are invalid, or if the resolved event stream +is not an async iterable. + +If the client-provided arguments to this function do not result in a +compliant subscription, a GraphQL Response (ExecutionResult) with +descriptive errors and no data will be returned. + +If the source stream could not be created due to faulty subscription +resolver logic or underlying systems, the promise will resolve to a single +ExecutionResult containing `errors` and no `data`. + +If the operation succeeded, the promise resolves to the AsyncIterable for the +event stream returned by the resolver. + +A Source Event Stream represents a sequence of events, each of which triggers +a GraphQL execution for that event. + +This may be useful when hosting the stateful subscription service in a +different process or machine than the stateless GraphQL execution engine, +or otherwise separating these two steps. For more on this, see the +"Supporting Subscriptions at Scale" information in the GraphQL specification. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
argsThe arguments used to perform the operation.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The source event stream, or an execution result containing subscription errors.
+ +
+ +
Example
+ +```ts +import { parse } from 'graphql/language'; +import { buildSchema } from 'graphql/utilities'; +import { createSourceEventStream } from 'graphql/execution'; + +async function* greetings() { + yield { greeting: 'Hello' }; +} + +const schema = buildSchema(` + type Query { + noop: String + } + + type Subscription { + greeting: String + } +`); + +const stream = await createSourceEventStream({ + schema, + document: parse('subscription { greeting }'), + rootValue: { greeting: () => greetings() }, +}); + +Symbol.asyncIterator in stream; // => true +``` + +
+ +
Overload 2
+ +Creates the source event stream for a subscription operation using the legacy +positional argument overload. This deprecated overload will be removed in the +next major version; use the args object overload instead. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
schemaGraphQL schema to use.
documentThe parsed GraphQL document containing the subscription
+operation.
rootValue?Initial root value passed to the subscription resolver.
contextValue?Application context value passed to resolvers.
variableValues?Runtime variable values keyed by variable name.
operationName?Name of the subscription operation to execute when
+the document contains multiple operations.
subscribeFieldResolver?Resolver used for the root subscription
+field.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The source event stream, or an execution result containing
+subscription errors.
+ +
+ +
Example
+ +```ts +import { parse } from 'graphql/language'; +import { buildSchema } from 'graphql/utilities'; +import { createSourceEventStream } from 'graphql/execution'; + +async function* greetings() { + yield { greeting: 'Hello' }; +} + +const schema = buildSchema(` + type Query { + noop: String + } + + type Subscription { + greeting: String + } +`); +const document = parse('subscription { greeting }'); + +const stream = await createSourceEventStream(schema, document, { + greeting: () => greetings(), +}); + +Symbol.asyncIterator in stream; // => true +``` + ## Types -### SubscriptionArgs Deprecated +### SubscriptionArgs **Interface.** Deprecated legacy alias for ExecutionArgs retained by the subscription module. Use [`ExecutionArgs`](/api-v16/execution#executionargs) directly instead because SubscriptionArgs will be diff --git a/website/pages/api-v16/type.mdx b/website/pages/api-v16/type.mdx index 07c243b495..a373adc391 100644 --- a/website/pages/api-v16/type.mdx +++ b/website/pages/api-v16/type.mdx @@ -245,8 +245,12 @@ assertEnumValueName('true'); // throws an error assertInputObjectType() + isListType() + assertListType() + isNonNullType() + assertNonNullType() isInputType() @@ -277,10 +281,14 @@ assertEnumValueName('true'); // throws an error assertNullableType() + getNullableType() + isNamedType() assertNamedType() + getNamedType() + resolveReadonlyArrayThunk() resolveObjMapThunk() @@ -4128,13 +4136,17 @@ assertInputObjectType(schema.getType('Review')); // throws an error
-#### assertListType() +#### isListType() -Returns the value as a GraphQLList, or throws if it is not one. +
+ +
Overload 1
+ +Returns true when the value is a GraphQLList. **Signature:** - +
@@ -4151,7 +4163,7 @@ Returns the value as a GraphQLList, or throws if it is not one. type - + The GraphQL type to inspect. @@ -4170,8 +4182,8 @@ Returns the value as a GraphQLList, or throws if it is not one. - - The value typed as a GraphQLList. + + True when the value is a GraphQLList. @@ -4181,23 +4193,31 @@ Returns the value as a GraphQLList, or throws if it is not one.
Example
```ts -import { GraphQLList, GraphQLString, assertListType } from 'graphql/type'; +import { buildSchema } from 'graphql/utilities'; +import { GraphQLList, GraphQLString, isListType } from 'graphql/type'; -const listType = assertListType(new GraphQLList(GraphQLString)); +const schema = buildSchema(` + type Query { + tags: [String!]! + } +`); -listType.ofType; // => GraphQLString -assertListType(GraphQLString); // throws an error +const tagsField = schema.getQueryType()?.getFields().tags; + +isListType(new GraphQLList(GraphQLString)); // => true +isListType(GraphQLString); // => false +isListType(tagsField?.type); // => false ``` -
+
-#### assertNonNullType() +
Overload 2
-Returns the value as a GraphQLNonNull, or throws if it is not one. +Returns true when the output type is a GraphQLList. **Signature:** - +
@@ -4214,8 +4234,8 @@ Returns the value as a GraphQLNonNull, or throws if it is not one. type - - The GraphQL type to inspect. + + The GraphQL output type to inspect. @@ -4233,8 +4253,8 @@ Returns the value as a GraphQLNonNull, or throws if it is not one. - - The value typed as a GraphQLNonNull. + + True when the output type is a list type. @@ -4244,23 +4264,30 @@ Returns the value as a GraphQLNonNull, or throws if it is not one.
Example
```ts -import { GraphQLNonNull, GraphQLString, assertNonNullType } from 'graphql/type'; +import { buildSchema } from 'graphql/utilities'; +import { getNullableType, isListType } from 'graphql/type'; -const nonNullType = assertNonNullType(new GraphQLNonNull(GraphQLString)); +const schema = buildSchema(` + type Query { + tags: [String!]! + } +`); -nonNullType.ofType; // => GraphQLString -assertNonNullType(GraphQLString); // throws an error +const tagsField = schema.getQueryType()?.getFields().tags; +const nullableTagsType = getNullableType(tagsField?.type); + +isListType(nullableTagsType); // => true ``` -
+
-#### isInputType() +
Overload 3
-Returns true when the value can be used as a GraphQL input type. +Returns true when the value is a GraphQLList. **Signature:** - +
@@ -4278,7 +4305,7 @@ Returns true when the value can be used as a GraphQL input type. type - The GraphQL type to inspect. + The value to inspect. @@ -4296,8 +4323,8 @@ Returns true when the value can be used as a GraphQL input type. - - True when the value can be used as a GraphQL input type. + + True when the value is a list type. @@ -4307,36 +4334,21 @@ Returns true when the value can be used as a GraphQL input type.
Example
```ts -import { buildSchema } from 'graphql/utilities'; -import { isInputType } from 'graphql/type'; - -const schema = buildSchema(` - input ReviewInput { - stars: Int! - } - - type Review { - stars: Int! - } - - type Query { - review(input: ReviewInput): Review - } -`); +import { isListType } from 'graphql/type'; -isInputType(schema.getType('ReviewInput')); // => true -isInputType(schema.getType('Review')); // => false +isListType('[String]'); // => false +isListType(null); // => false ```
-#### assertInputType() +#### assertListType() -Returns the value as a GraphQL input type, or throws if it is not one. +Returns the value as a GraphQLList, or throws if it is not one. **Signature:** - +
@@ -4372,8 +4384,8 @@ Returns the value as a GraphQL input type, or throws if it is not one. - - The value typed as a GraphQL input type. + + The value typed as a GraphQLList. @@ -4383,38 +4395,27 @@ Returns the value as a GraphQL input type, or throws if it is not one.
Example
```ts -import { buildSchema } from 'graphql/utilities'; -import { assertInputType } from 'graphql/type'; - -const schema = buildSchema(` - input ReviewInput { - stars: Int! - } - - type Review { - stars: Int! - } - - type Query { - review(input: ReviewInput): Review - } -`); +import { GraphQLList, GraphQLString, assertListType } from 'graphql/type'; -const inputType = assertInputType(schema.getType('ReviewInput')); +const listType = assertListType(new GraphQLList(GraphQLString)); -inputType.toString(); // => 'ReviewInput' -assertInputType(schema.getType('Review')); // throws an error +listType.ofType; // => GraphQLString +assertListType(GraphQLString); // throws an error ```
-#### isOutputType() +#### isNonNullType() -Returns true when the value can be used as a GraphQL output type. +
+ +
Overload 1
+ +Returns true when the value is a GraphQLNonNull. **Signature:** - +
@@ -4431,7 +4432,7 @@ Returns true when the value can be used as a GraphQL output type. type - + The GraphQL type to inspect. @@ -4450,8 +4451,8 @@ Returns true when the value can be used as a GraphQL output type. - - True when the value can be used as a GraphQL output type. + + True when the value is a GraphQLNonNull. @@ -4462,35 +4463,31 @@ Returns true when the value can be used as a GraphQL output type. ```ts import { buildSchema } from 'graphql/utilities'; -import { isOutputType } from 'graphql/type'; +import { GraphQLNonNull, GraphQLString, isNonNullType } from 'graphql/type'; const schema = buildSchema(` - input ReviewInput { - stars: Int! - } - - type Review { - stars: Int! - } - type Query { - review(input: ReviewInput): Review + name: String! + nickname: String } `); -isOutputType(schema.getType('Review')); // => true -isOutputType(schema.getType('ReviewInput')); // => false +const fields = schema.getQueryType()?.getFields(); + +isNonNullType(new GraphQLNonNull(GraphQLString)); // => true +isNonNullType(fields?.name.type); // => true +isNonNullType(fields?.nickname.type); // => false ``` -
+
-#### assertOutputType() +
Overload 2
-Returns the value as a GraphQL output type, or throws if it is not one. +Returns true when the output type is a GraphQLNonNull. **Signature:** - +
@@ -4507,8 +4504,8 @@ Returns the value as a GraphQL output type, or throws if it is not one. type - - The GraphQL type to inspect. + + The GraphQL output type to inspect. @@ -4526,8 +4523,8 @@ Returns the value as a GraphQL output type, or throws if it is not one. - - The value typed as a GraphQL output type. + + True when the output type is a non-null type. @@ -4538,37 +4535,30 @@ Returns the value as a GraphQL output type, or throws if it is not one. ```ts import { buildSchema } from 'graphql/utilities'; -import { assertOutputType } from 'graphql/type'; +import { isNonNullType } from 'graphql/type'; const schema = buildSchema(` - input ReviewInput { - stars: Int! - } - - type Review { - stars: Int! - } - type Query { - review(input: ReviewInput): Review + name: String! + nickname: String } `); -const outputType = assertOutputType(schema.getType('Review')); +const fields = schema.getQueryType()?.getFields(); -outputType.toString(); // => 'Review' -assertOutputType(schema.getType('ReviewInput')); // throws an error +isNonNullType(fields?.name.type); // => true +isNonNullType(fields?.nickname.type); // => false ``` -
+
-#### isLeafType() +
Overload 3
-Returns true when the value is a GraphQL scalar or enum type. +Returns true when the value is a GraphQLNonNull. **Signature:** - +
@@ -4586,7 +4576,7 @@ Returns true when the value is a GraphQL scalar or enum type. type - The GraphQL type to inspect. + The value to inspect. @@ -4604,8 +4594,8 @@ Returns true when the value is a GraphQL scalar or enum type. - - True when the value is a GraphQL scalar or enum type. + + True when the value is a non-null type. @@ -4615,38 +4605,21 @@ Returns true when the value is a GraphQL scalar or enum type.
Example
```ts -import { buildSchema } from 'graphql/utilities'; -import { isLeafType } from 'graphql/type'; - -const schema = buildSchema(` - enum Episode { - NEW_HOPE - } - - type Review { - stars: Int! - } +import { isNonNullType } from 'graphql/type'; - type Query { - episode: Episode - review: Review - } -`); - -isLeafType(schema.getType('Episode')); // => true -isLeafType(schema.getType('String')); // => true -isLeafType(schema.getType('Review')); // => false +isNonNullType('String!'); // => false +isNonNullType(null); // => false ```
-#### assertLeafType() +#### assertNonNullType() -Returns the value as a GraphQL leaf type, or throws if it is not one. +Returns the value as a GraphQLNonNull, or throws if it is not one. **Signature:** - +
@@ -4682,8 +4655,8 @@ Returns the value as a GraphQL leaf type, or throws if it is not one. - - The value typed as a GraphQL leaf type. + + The value typed as a GraphQLNonNull. @@ -4693,39 +4666,23 @@ Returns the value as a GraphQL leaf type, or throws if it is not one.
Example
```ts -import { buildSchema } from 'graphql/utilities'; -import { assertLeafType } from 'graphql/type'; - -const schema = buildSchema(` - enum Episode { - NEW_HOPE - } - - type Review { - stars: Int! - } - - type Query { - episode: Episode - review: Review - } -`); +import { GraphQLNonNull, GraphQLString, assertNonNullType } from 'graphql/type'; -const episodeType = assertLeafType(schema.getType('Episode')); +const nonNullType = assertNonNullType(new GraphQLNonNull(GraphQLString)); -episodeType.toString(); // => 'Episode' -assertLeafType(schema.getType('Review')); // throws an error +nonNullType.ofType; // => GraphQLString +assertNonNullType(GraphQLString); // throws an error ```
-#### isCompositeType() +#### isInputType() -Returns true when the value is a GraphQL object, interface, or union type. +Returns true when the value can be used as a GraphQL input type. **Signature:** - +
@@ -4761,8 +4718,8 @@ Returns true when the value is a GraphQL object, interface, or union type. - - True when the value is a GraphQL object, interface, or union type. + + True when the value can be used as a GraphQL input type. @@ -4773,40 +4730,35 @@ Returns true when the value is a GraphQL object, interface, or union type. ```ts import { buildSchema } from 'graphql/utilities'; -import { isCompositeType } from 'graphql/type'; +import { isInputType } from 'graphql/type'; const schema = buildSchema(` - interface Node { - id: ID! + input ReviewInput { + stars: Int! } - type User implements Node { - id: ID! + type Review { + stars: Int! } - union SearchResult = User - type Query { - node: Node - search: [SearchResult] + review(input: ReviewInput): Review } `); -isCompositeType(schema.getType('User')); // => true -isCompositeType(schema.getType('Node')); // => true -isCompositeType(schema.getType('SearchResult')); // => true -isCompositeType(schema.getType('String')); // => false +isInputType(schema.getType('ReviewInput')); // => true +isInputType(schema.getType('Review')); // => false ```
-#### assertCompositeType() +#### assertInputType() -Returns the value as a GraphQL composite type, or throws if it is not one. +Returns the value as a GraphQL input type, or throws if it is not one. **Signature:** - +
@@ -4842,8 +4794,8 @@ Returns the value as a GraphQL composite type, or throws if it is not one. - - The value typed as a GraphQL composite type. + + The value typed as a GraphQL input type. @@ -4854,37 +4806,993 @@ Returns the value as a GraphQL composite type, or throws if it is not one. ```ts import { buildSchema } from 'graphql/utilities'; -import { assertCompositeType } from 'graphql/type'; +import { assertInputType } from 'graphql/type'; const schema = buildSchema(` - interface Node { - id: ID! + input ReviewInput { + stars: Int! } - type User implements Node { - id: ID! + type Review { + stars: Int! } type Query { - node: Node + review(input: ReviewInput): Review } `); -const userType = assertCompositeType(schema.getType('User')); +const inputType = assertInputType(schema.getType('ReviewInput')); -userType.toString(); // => 'User' -assertCompositeType(schema.getType('String')); // throws an error +inputType.toString(); // => 'ReviewInput' +assertInputType(schema.getType('Review')); // throws an error +``` + +
+ +#### isOutputType() + +Returns true when the value can be used as a GraphQL output type. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
True when the value can be used as a GraphQL output type.
+ +
+ +
Example
+ +```ts +import { buildSchema } from 'graphql/utilities'; +import { isOutputType } from 'graphql/type'; + +const schema = buildSchema(` + input ReviewInput { + stars: Int! + } + + type Review { + stars: Int! + } + + type Query { + review(input: ReviewInput): Review + } +`); + +isOutputType(schema.getType('Review')); // => true +isOutputType(schema.getType('ReviewInput')); // => false +``` + +
+ +#### assertOutputType() + +Returns the value as a GraphQL output type, or throws if it is not one. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The value typed as a GraphQL output type.
+ +
+ +
Example
+ +```ts +import { buildSchema } from 'graphql/utilities'; +import { assertOutputType } from 'graphql/type'; + +const schema = buildSchema(` + input ReviewInput { + stars: Int! + } + + type Review { + stars: Int! + } + + type Query { + review(input: ReviewInput): Review + } +`); + +const outputType = assertOutputType(schema.getType('Review')); + +outputType.toString(); // => 'Review' +assertOutputType(schema.getType('ReviewInput')); // throws an error +``` + +
+ +#### isLeafType() + +Returns true when the value is a GraphQL scalar or enum type. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
True when the value is a GraphQL scalar or enum type.
+ +
+ +
Example
+ +```ts +import { buildSchema } from 'graphql/utilities'; +import { isLeafType } from 'graphql/type'; + +const schema = buildSchema(` + enum Episode { + NEW_HOPE + } + + type Review { + stars: Int! + } + + type Query { + episode: Episode + review: Review + } +`); + +isLeafType(schema.getType('Episode')); // => true +isLeafType(schema.getType('String')); // => true +isLeafType(schema.getType('Review')); // => false ```
-#### isAbstractType() +#### assertLeafType() + +Returns the value as a GraphQL leaf type, or throws if it is not one. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The value typed as a GraphQL leaf type.
+ +
+ +
Example
+ +```ts +import { buildSchema } from 'graphql/utilities'; +import { assertLeafType } from 'graphql/type'; + +const schema = buildSchema(` + enum Episode { + NEW_HOPE + } + + type Review { + stars: Int! + } + + type Query { + episode: Episode + review: Review + } +`); + +const episodeType = assertLeafType(schema.getType('Episode')); + +episodeType.toString(); // => 'Episode' +assertLeafType(schema.getType('Review')); // throws an error +``` + +
+ +#### isCompositeType() + +Returns true when the value is a GraphQL object, interface, or union type. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
True when the value is a GraphQL object, interface, or union type.
+ +
+ +
Example
+ +```ts +import { buildSchema } from 'graphql/utilities'; +import { isCompositeType } from 'graphql/type'; + +const schema = buildSchema(` + interface Node { + id: ID! + } + + type User implements Node { + id: ID! + } + + union SearchResult = User + + type Query { + node: Node + search: [SearchResult] + } +`); + +isCompositeType(schema.getType('User')); // => true +isCompositeType(schema.getType('Node')); // => true +isCompositeType(schema.getType('SearchResult')); // => true +isCompositeType(schema.getType('String')); // => false +``` + +
+ +#### assertCompositeType() + +Returns the value as a GraphQL composite type, or throws if it is not one. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The value typed as a GraphQL composite type.
+ +
+ +
Example
+ +```ts +import { buildSchema } from 'graphql/utilities'; +import { assertCompositeType } from 'graphql/type'; + +const schema = buildSchema(` + interface Node { + id: ID! + } + + type User implements Node { + id: ID! + } + + type Query { + node: Node + } +`); + +const userType = assertCompositeType(schema.getType('User')); + +userType.toString(); // => 'User' +assertCompositeType(schema.getType('String')); // throws an error +``` + +
+ +#### isAbstractType() + +Returns true when the value is a GraphQL interface or union type. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
True when the value is a GraphQL interface or union type.
+ +
+ +
Example
+ +```ts +import { buildSchema } from 'graphql/utilities'; +import { isAbstractType } from 'graphql/type'; + +const schema = buildSchema(` + interface Node { + id: ID! + } + + type User implements Node { + id: ID! + } + + union SearchResult = User + + type Query { + node: Node + search: [SearchResult] + } +`); + +isAbstractType(schema.getType('Node')); // => true +isAbstractType(schema.getType('SearchResult')); // => true +isAbstractType(schema.getType('User')); // => false +``` + +
+ +#### assertAbstractType() + +Returns the value as a GraphQL abstract type, or throws if it is not one. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The value typed as a GraphQL abstract type.
+ +
+ +
Example
+ +```ts +import { buildSchema } from 'graphql/utilities'; +import { assertAbstractType } from 'graphql/type'; + +const schema = buildSchema(` + interface Node { + id: ID! + } + + type User implements Node { + id: ID! + } + + type Query { + node: Node + } +`); + +const nodeType = assertAbstractType(schema.getType('Node')); + +nodeType.toString(); // => 'Node' +assertAbstractType(schema.getType('User')); // throws an error +``` + +
+ +#### isWrappingType() + +Returns true when the value is a GraphQL list or non-null wrapper type. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
True when the value is a GraphQL list or non-null wrapper type.
+ +
+ +
Example
+ +```ts +import { + GraphQLList, + GraphQLNonNull, + GraphQLString, + isWrappingType, +} from 'graphql/type'; + +isWrappingType(new GraphQLList(GraphQLString)); // => true +isWrappingType(new GraphQLNonNull(GraphQLString)); // => true +isWrappingType(GraphQLString); // => false +``` + +
+ +#### assertWrappingType() + +Returns the value as a GraphQL wrapping type, or throws if it is not one. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The value typed as a GraphQL wrapping type.
+ +
+ +
Example
+ +```ts +import { GraphQLList, GraphQLString, assertWrappingType } from 'graphql/type'; + +const wrappingType = assertWrappingType(new GraphQLList(GraphQLString)); + +wrappingType.toString(); // => '[String]' +assertWrappingType(GraphQLString); // throws an error +``` + +
+ +#### isNullableType() + +Returns true when the value is a GraphQL type that can accept null. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
True when the value is a GraphQL type that can accept null.
+ +
+ +
Example
+ +```ts +import { GraphQLNonNull, GraphQLString, isNullableType } from 'graphql/type'; + +isNullableType(GraphQLString); // => true +isNullableType(new GraphQLNonNull(GraphQLString)); // => false +isNullableType(null); // => false +``` + +
+ +#### assertNullableType() + +Returns the value as a nullable GraphQL type, or throws if it is not one. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The value typed as a nullable GraphQL type.
+ +
+ +
Example
+ +```ts +import { + GraphQLNonNull, + GraphQLString, + assertNullableType, +} from 'graphql/type'; + +const nullableType = assertNullableType(GraphQLString); + +nullableType; // => GraphQLString +assertNullableType(new GraphQLNonNull(GraphQLString)); // throws an error +``` + +
+ +#### getNullableType() + +
+ +
Overload 1
+ +Returns the nullable type. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Example
+ +```ts +import { getNullableType } from 'graphql/type'; + +getNullableType(null); // => undefined +getNullableType(undefined); // => undefined +``` + +
+ +
Overload 2
+ +Returns the nullable type after removing one non-null wrapper. + +
+ +
Type Parameters
-Returns true when the value is a GraphQL interface or union type. + + + + + + + + + + + + + + + + + +
NameConstraintDefaultDescription
TThe nullable GraphQL type returned after removing one non-null wrapper.
**Signature:** - +
@@ -4901,8 +5809,8 @@ Returns true when the value is a GraphQL interface or union type. type - - The GraphQL type to inspect. + + A nullable type or non-null wrapper. @@ -4920,8 +5828,8 @@ Returns true when the value is a GraphQL interface or union type. - - True when the value is a GraphQL interface or union type. + + The nullable type after removing one non-null wrapper, if present. @@ -4931,40 +5839,29 @@ Returns true when the value is a GraphQL interface or union type.
Example
```ts -import { buildSchema } from 'graphql/utilities'; -import { isAbstractType } from 'graphql/type'; - -const schema = buildSchema(` - interface Node { - id: ID! - } - - type User implements Node { - id: ID! - } - - union SearchResult = User +import { + GraphQLList, + GraphQLNonNull, + GraphQLString, + getNullableType, +} from 'graphql/type'; - type Query { - node: Node - search: [SearchResult] - } -`); +const requiredString = new GraphQLNonNull(GraphQLString); +const stringList = new GraphQLList(GraphQLString); -isAbstractType(schema.getType('Node')); // => true -isAbstractType(schema.getType('SearchResult')); // => true -isAbstractType(schema.getType('User')); // => false +getNullableType(requiredString); // => GraphQLString +getNullableType(stringList); // => stringList ``` -
+
-#### assertAbstractType() +
Overload 3
-Returns the value as a GraphQL abstract type, or throws if it is not one. +Returns the nullable type after removing one non-null wrapper. **Signature:** - +
@@ -4981,7 +5878,7 @@ Returns the value as a GraphQL abstract type, or throws if it is not one. type - + The GraphQL type to inspect. @@ -5000,8 +5897,8 @@ Returns the value as a GraphQL abstract type, or throws if it is not one. - - The value typed as a GraphQL abstract type. + + The nullable type after removing one non-null wrapper, if present. @@ -5011,38 +5908,30 @@ Returns the value as a GraphQL abstract type, or throws if it is not one.
Example
```ts -import { buildSchema } from 'graphql/utilities'; -import { assertAbstractType } from 'graphql/type'; - -const schema = buildSchema(` - interface Node { - id: ID! - } - - type User implements Node { - id: ID! - } - - type Query { - node: Node - } -`); +import { + GraphQLList, + GraphQLNonNull, + GraphQLString, + getNullableType, +} from 'graphql/type'; -const nodeType = assertAbstractType(schema.getType('Node')); +const requiredStringList = new GraphQLNonNull( + new GraphQLList(GraphQLString), +); -nodeType.toString(); // => 'Node' -assertAbstractType(schema.getType('User')); // throws an error +getNullableType(requiredStringList).toString(); // => '[String]' +getNullableType(GraphQLString); // => GraphQLString ```
-#### isWrappingType() +#### isNamedType() -Returns true when the value is a GraphQL list or non-null wrapper type. +Returns true when the value is a GraphQL named type. **Signature:** - +
@@ -5078,8 +5967,8 @@ Returns true when the value is a GraphQL list or non-null wrapper type. - - True when the value is a GraphQL list or non-null wrapper type. + + True when the value is a GraphQL named type. @@ -5089,27 +5978,22 @@ Returns true when the value is a GraphQL list or non-null wrapper type.
Example
```ts -import { - GraphQLList, - GraphQLNonNull, - GraphQLString, - isWrappingType, -} from 'graphql/type'; +import { GraphQLList, GraphQLString, isNamedType } from 'graphql/type'; -isWrappingType(new GraphQLList(GraphQLString)); // => true -isWrappingType(new GraphQLNonNull(GraphQLString)); // => true -isWrappingType(GraphQLString); // => false +isNamedType(GraphQLString); // => true +isNamedType(new GraphQLList(GraphQLString)); // => false +isNamedType(null); // => false ```
-#### assertWrappingType() +#### assertNamedType() -Returns the value as a GraphQL wrapping type, or throws if it is not one. +Returns the value as a GraphQL named type, or throws if it is not one. **Signature:** - +
@@ -5145,8 +6029,8 @@ Returns the value as a GraphQL wrapping type, or throws if it is not one. - - The value typed as a GraphQL wrapping type. + + The value typed as a GraphQL named type. @@ -5156,23 +6040,27 @@ Returns the value as a GraphQL wrapping type, or throws if it is not one.
Example
```ts -import { GraphQLList, GraphQLString, assertWrappingType } from 'graphql/type'; +import { GraphQLList, GraphQLString, assertNamedType } from 'graphql/type'; -const wrappingType = assertWrappingType(new GraphQLList(GraphQLString)); +const namedType = assertNamedType(GraphQLString); -wrappingType.toString(); // => '[String]' -assertWrappingType(GraphQLString); // throws an error +namedType.name; // => 'String' +assertNamedType(new GraphQLList(GraphQLString)); // throws an error ```
-#### isNullableType() +#### getNamedType() -Returns true when the value is a GraphQL type that can accept null. +
+ +
Overload 1
+ +Returns the named type. **Signature:** - +
@@ -5189,7 +6077,7 @@ Returns true when the value is a GraphQL type that can accept null. type - + The GraphQL type to inspect. @@ -5197,6 +6085,48 @@ Returns true when the value is a GraphQL type that can accept null.
+
Example
+ +```ts +import { getNamedType } from 'graphql/type'; + +getNamedType(null); // => undefined +getNamedType(undefined); // => undefined +``` + +
+ +
Overload 2
+ +Returns the named input type after unwrapping all list and non-null wrappers. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL input type to inspect.
+ +
+
Returns
@@ -5208,8 +6138,8 @@ Returns true when the value is a GraphQL type that can accept null. - - + +
True when the value is a GraphQL type that can accept null.The named input type after unwrapping all wrappers.
@@ -5219,22 +6149,33 @@ Returns true when the value is a GraphQL type that can accept null.
Example
```ts -import { GraphQLNonNull, GraphQLString, isNullableType } from 'graphql/type'; +import { buildSchema } from 'graphql/utilities'; +import { getNamedType } from 'graphql/type'; -isNullableType(GraphQLString); // => true -isNullableType(new GraphQLNonNull(GraphQLString)); // => false -isNullableType(null); // => false +const schema = buildSchema(` + input ReviewInput { + stars: Int! + } + + type Query { + review(input: [ReviewInput!]!): Boolean + } +`); + +const inputArg = schema.getQueryType()?.getFields().review.args[0]; + +getNamedType(inputArg?.type).toString(); // => 'ReviewInput' ``` -
+
-#### assertNullableType() +
Overload 3
-Returns the value as a nullable GraphQL type, or throws if it is not one. +Returns the named output type after unwrapping all list and non-null wrappers. **Signature:** - +
@@ -5251,8 +6192,8 @@ Returns the value as a nullable GraphQL type, or throws if it is not one. type - - The GraphQL type to inspect. + + The GraphQL output type to inspect. @@ -5270,8 +6211,8 @@ Returns the value as a nullable GraphQL type, or throws if it is not one. - - The value typed as a nullable GraphQL type. + + The named output type after unwrapping all wrappers. @@ -5281,27 +6222,33 @@ Returns the value as a nullable GraphQL type, or throws if it is not one.
Example
```ts -import { - GraphQLNonNull, - GraphQLString, - assertNullableType, -} from 'graphql/type'; +import { buildSchema } from 'graphql/utilities'; +import { getNamedType } from 'graphql/type'; -const nullableType = assertNullableType(GraphQLString); +const schema = buildSchema(` + type User { + name: String + } -nullableType; // => GraphQLString -assertNullableType(new GraphQLNonNull(GraphQLString)); // throws an error + type Query { + users: [User!]! + } +`); + +const usersField = schema.getQueryType()?.getFields().users; + +getNamedType(usersField?.type).toString(); // => 'User' ``` -
+
-#### isNamedType() +
Overload 4
-Returns true when the value is a GraphQL named type. +Returns the named type after unwrapping all list and non-null wrappers. **Signature:** - +
@@ -5318,7 +6265,7 @@ Returns true when the value is a GraphQL named type. type - + The GraphQL type to inspect. @@ -5337,8 +6284,8 @@ Returns true when the value is a GraphQL named type. - - True when the value is a GraphQL named type. + + The named type after unwrapping all wrappers. @@ -5348,22 +6295,29 @@ Returns true when the value is a GraphQL named type.
Example
```ts -import { GraphQLList, GraphQLString, isNamedType } from 'graphql/type'; +import { + GraphQLList, + GraphQLNonNull, + GraphQLString, + getNamedType, +} from 'graphql/type'; -isNamedType(GraphQLString); // => true -isNamedType(new GraphQLList(GraphQLString)); // => false -isNamedType(null); // => false +const nestedType = new GraphQLNonNull( + new GraphQLList(new GraphQLNonNull(GraphQLString)), +); + +getNamedType(nestedType); // => GraphQLString ``` -
+
-#### assertNamedType() +
Overload 5
-Returns the value as a GraphQL named type, or throws if it is not one. +Returns the named type after unwrapping all list and non-null wrappers. **Signature:** - +
@@ -5380,7 +6334,7 @@ Returns the value as a GraphQL named type, or throws if it is not one. type - + The GraphQL type to inspect. @@ -5399,8 +6353,8 @@ Returns the value as a GraphQL named type, or throws if it is not one. - - The value typed as a GraphQL named type. + + The named type after unwrapping all wrappers, or undefined for nullish input. @@ -5410,12 +6364,14 @@ Returns the value as a GraphQL named type, or throws if it is not one.
Example
```ts -import { GraphQLList, GraphQLString, assertNamedType } from 'graphql/type'; - -const namedType = assertNamedType(GraphQLString); +import { + GraphQLList, + GraphQLString, + getNamedType, +} from 'graphql/type'; -namedType.name; // => 'String' -assertNamedType(new GraphQLList(GraphQLString)); // throws an error +getNamedType(new GraphQLList(GraphQLString)); // => GraphQLString +getNamedType(undefined); // => undefined ```
diff --git a/website/pages/api-v16/utilities.mdx b/website/pages/api-v16/utilities.mdx index dd5e26afc4..6d1d67f1cf 100644 --- a/website/pages/api-v16/utilities.mdx +++ b/website/pages/api-v16/utilities.mdx @@ -826,15 +826,15 @@ fields; // => [{ name: 'greeting', parentType: 'Query', type: 'String' }] ### Functions -#### assertValidName() Deprecated +#### assertValidName() Upholds the spec rules about naming. This deprecated helper is retained for backwards compatibility; call [`assertName`](/api-v16/type#assertname) instead because assertValidName @@ -897,7 +897,7 @@ assertValidName('__typename'); // throws an error
-#### isValidNameError() Deprecated +#### isValidNameError() Returns an Error if a name is invalid. This deprecated helper is retained for backwards compatibility; call [`assertName`](/api-v16/type#assertname) and catch the thrown GraphQLError @@ -969,6 +969,8 @@ error.message; // => 'Name "__typename" must not begin with "__", which is reser coerceInputValue() + typeFromAST() + valueFromAST() valueFromASTUntyped() @@ -1193,6 +1195,314 @@ errors; // => [ { path: [], invalidValue: null, message: 'Expected non-nullable
+#### typeFromAST() + +
+ +
Overload 1
+ +Given a Schema and an AST node describing a type, return a GraphQLType +definition which applies to that type. For example, if provided the parsed +AST node for `[User]`, a GraphQLList instance will be returned, containing +the type called "User" found in the schema. If a type called "User" is not +found in the schema, then undefined will be returned. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
schemaGraphQL schema to use.
typeNodeThe GraphQL type AST node to resolve.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The GraphQL type referenced by the AST node, or undefined if it cannot be resolved.
+ +
+ +
Example
+ +```ts +import { parseType } from 'graphql/language'; +import { buildSchema, typeFromAST } from 'graphql/utilities'; + +const schema = buildSchema(` + type Query { + name: String + } +`); + +typeFromAST(schema, parseType('String'))?.toString(); // => 'String' +typeFromAST(schema, parseType('Missing')); // => undefined +``` + +
+ +
Overload 2
+ +Resolves a list type AST node against a schema. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
schemaGraphQL schema to use.
typeNodeThe list type AST node to resolve.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The GraphQL list type referenced by the AST node, or undefined if
+it cannot be resolved.
+ +
+ +
Example
+ +```ts +import { parseType } from 'graphql/language'; +import { buildSchema, typeFromAST } from 'graphql/utilities'; + +const schema = buildSchema(` + type Query { + tags: [String] + } +`); + +typeFromAST(schema, parseType('[String]'))?.toString(); // => '[String]' +typeFromAST(schema, parseType('[Missing]')); // => undefined +``` + +
+ +
Overload 3
+ +Resolves a non-null type AST node against a schema. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
schemaGraphQL schema to use.
typeNodeThe non-null type AST node to resolve.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The GraphQL non-null type referenced by the AST node, or undefined
+if it cannot be resolved.
+ +
+ +
Example
+ +```ts +import { parseType } from 'graphql/language'; +import { buildSchema, typeFromAST } from 'graphql/utilities'; + +const schema = buildSchema(` + type Query { + name: String! + } +`); + +typeFromAST(schema, parseType('String!'))?.toString(); // => 'String!' +typeFromAST(schema, parseType('[String!]!'))?.toString(); // => '[String!]!' +``` + +
+ +
Overload 4
+ +Resolves a type AST node against a schema. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
schemaGraphQL schema to use.
typeNodeThe GraphQL type AST node to resolve.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The GraphQL type referenced by the AST node, or undefined if it
+cannot be resolved.
+ +
+ +
Example
+ +```ts +import { parseType } from 'graphql/language'; +import { buildSchema, typeFromAST } from 'graphql/utilities'; + +const schema = buildSchema(` + type User { + name: String + } + + type Query { + users: [User!]! + } +`); + +typeFromAST(schema, parseType('User'))?.toString(); // => 'User' +typeFromAST(schema, parseType('[User!]!'))?.toString(); // => '[User!]!' +typeFromAST(schema, parseType('Missing')); // => undefined +``` + +
+ #### valueFromAST() Produces a JavaScript value given a GraphQL Value AST. @@ -3738,7 +4048,7 @@ changes[0].description; // matches /EMPIRE was added/ Functions:
getOperationAST() - getOperationRootType() + getOperationRootType()

@@ -3816,7 +4126,7 @@ getOperationAST(document, 'Missing'); // => undefined
-#### getOperationRootType() Deprecated +#### getOperationRootType() Extracts the root type of the operation from the schema. This deprecated helper is retained for backwards compatibility; call diff --git a/website/pages/api-v17/error.mdx b/website/pages/api-v17/error.mdx index 689130b992..84e57ffff8 100644 --- a/website/pages/api-v17/error.mdx +++ b/website/pages/api-v17/error.mdx @@ -124,7 +124,7 @@ represent nodes after the first node. which correspond to this error. - originalError + originalError Original error that caused this GraphQLError, if one exists.
Deprecated in favor of {"cause"} to better align with JavaScript standards. @@ -444,7 +444,7 @@ an object which can contain all the values you need. Response path where this error occurred during execution. - originalError? + originalError? Original error that caused this GraphQLError, if one exists.
Deprecated in favor of {"cause"} to better align with JavaScript standards. diff --git a/website/pages/api-v17/language.mdx b/website/pages/api-v17/language.mdx index 8095c6c15b..de353e40b3 100644 --- a/website/pages/api-v17/language.mdx +++ b/website/pages/api-v17/language.mdx @@ -5522,6 +5522,8 @@ text; // => '{\n hero {\n name\n }\n}'

Functions:
+ visit() + visitInParallel() getEnterLeaveForKind() @@ -5542,6 +5544,334 @@ text; // => '{\n hero {\n name\n }\n}' ### Functions +#### visit() + +


+ +
Overload 1
+ +visit() will walk through an AST using a depth-first traversal, calling +the visitor's enter function at each node in the traversal, and calling the +leave function after visiting that node and all of its child nodes. + +By returning different values from the enter and leave functions, the +behavior of the visitor can be altered, including skipping over a sub-tree of +the AST (by returning false), editing the AST by returning a value or null +to remove the value, or to stop the whole traversal by returning BREAK. + +When using visit() to edit an AST, the original AST will not be modified, and +a new version of the AST with the changes applied will be returned from the +visit function. + +
+ +
Type Parameters
+ + + + + + + + + + + + + + + + + + +
NameConstraintDefaultDescription
NThe root AST node type returned when visiting without reducing.
+ +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDefaultDescription
rootThe AST node at which to start traversal.
visitorThe visitor or reducer functions to call while traversing.
visitorKeys?Optional map of child keys to visit for each AST node kind.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The original AST, an edited AST, or a reduced value depending on the visitor.
+ +
+ +
Example 1
+ +```ts +// Return values control traversal: undefined makes no change, false skips +// a subtree, BREAK stops traversal, null removes a node, and any other +// value replaces the current node. +import { Kind, parse, print, visit } from 'graphql/language'; + +const document = parse('{ hero { name } }'); +const editedAST = visit(document, { + Field: (node) => { + if (node.name.value === 'hero') { + return { + ...node, + name: { kind: Kind.NAME, value: 'human' }, + }; + } + }, +}); + +print(editedAST); // => '{\n human {\n name\n }\n}' +``` + +
+ +
Example 2
+ +```ts +// A named visitor function runs when entering nodes of that kind. +import { parse, visit } from 'graphql/language'; + +const document = parse('{ hero { name } }'); +const fieldNames = []; + +visit(document, { + Field: (node) => { + fieldNames.push(node.name.value); + }, +}); + +fieldNames; // => ['hero', 'name'] +``` + +
+ +
Example 3
+ +```ts +// A named visitor object can provide separate enter and leave handlers for +// nodes of that kind. +import { parse, visit } from 'graphql/language'; + +const document = parse('{ hero { name } }'); +const events = []; + +visit(document, { + Field: { + enter: (node) => { + events.push(`enter:${node.name.value}`); + }, + leave: (node) => { + events.push(`leave:${node.name.value}`); + }, + }, +}); + +events; // => ['enter:hero', 'enter:name', 'leave:name', 'leave:hero'] +``` + +
+ +
Example 4
+ +```ts +// Generic enter and leave handlers run for every node. +import { parse, visit } from 'graphql/language'; + +const document = parse('{ hero { name } }'); +let enterCount = 0; +let leaveCount = 0; + +visit(document, { + enter: (node) => { + enterCount += 1; + }, + leave: (node) => { + leaveCount += 1; + }, +}); + +enterCount; // => leaveCount +enterCount > 0; // => true +``` + +
+ +
Overload 2
+ +Traverses an AST with reducer callbacks and returns the reduced value. + +
+ +
Type Parameters
+ + + + + + + + + + + + + + + + + + +
NameConstraintDefaultDescription
RThe value produced by reducer visitor callbacks.
+ +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDefaultDescription
rootThe AST node where traversal starts.
visitorReducer callbacks to invoke during traversal.
visitorKeys?Optional mapping of child keys for each AST node kind.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The value produced by the reducer visitor.
+ +
+ +
Example
+ +```ts +// A reducer visitor returns values from leave handlers to build a reduced +// result instead of returning an edited AST. +import { parse, visit } from 'graphql/language'; + +const document = parse('{ hero { name } }'); +const printed = visit(document, { + Name: { + leave: (node) => { + return node.value; + }, + }, + Field: { + leave: (node) => { + return node.selectionSet == null + ? node.name + : `${node.name} { ${node.selectionSet} }`; + }, + }, + SelectionSet: { + leave: (node) => { + return node.selections.join(' '); + }, + }, + OperationDefinition: { + leave: (node) => { + return node.selectionSet; + }, + }, + Document: { + leave: (node) => { + return node.definitions.join('\n'); + }, + }, +}); + +printed; // => 'hero { name }' +``` + +
+ #### visitInParallel() Creates a new visitor instance which delegates to many visitors to run in diff --git a/website/pages/api-v17/type.mdx b/website/pages/api-v17/type.mdx index d36821a452..41cc7ee25a 100644 --- a/website/pages/api-v17/type.mdx +++ b/website/pages/api-v17/type.mdx @@ -261,8 +261,12 @@ assertEnumValueName('true'); // throws an error assertInputField() + isListType() + assertListType() + isNonNullType() + assertNonNullType() isInputType() @@ -293,10 +297,14 @@ assertEnumValueName('true'); // throws an error assertNullableType() + getNullableType() + isNamedType() assertNamedType() + getNamedType() + resolveReadonlyArrayThunk() resolveObjMapThunk() @@ -339,15 +347,15 @@ assertEnumValueName('true'); // throws an error GraphQLScalarTypeExtensions - GraphQLScalarSerializer + GraphQLScalarSerializer GraphQLScalarOutputValueCoercer - GraphQLScalarValueParser + GraphQLScalarValueParser GraphQLScalarInputValueCoercer - GraphQLScalarLiteralParser + GraphQLScalarLiteralParser GraphQLScalarInputLiteralCoercer @@ -969,19 +977,19 @@ Creates a GraphQLScalarType instance. URL identifying the behavior specified for this custom scalar. - serialize + serialize Deprecated legacy serializer used to convert internal values for response
output. Use {"coerceOutputValue()"} instead. - parseValue + parseValue Deprecated legacy parser used to convert externally provided input values.
Use {"coerceInputValue()"} instead. - parseLiteral + parseLiteral Deprecated legacy parser used to convert externally provided input
literals. Use {"replaceVariables()"} and {"coerceInputLiteral()"} instead. @@ -2562,7 +2570,7 @@ Episode.getValue('JEDI'); // => undefined
-##### serialize() Deprecated +##### serialize() Serializes a runtime enum value as a GraphQL enum name. @@ -2704,7 +2712,7 @@ RGB.coerceOutputValue(3); // throws an error
-##### parseValue() Deprecated +##### parseValue() Deprecated legacy enum parser for externally provided input values. Use `coerceInputValue()` instead. @@ -2856,7 +2864,7 @@ RGB.coerceInputValue(2); // throws an error
-##### parseLiteral() Deprecated +##### parseLiteral() Deprecated legacy enum parser for externally provided input literals. Use `coerceInputLiteral()` instead. @@ -5121,13 +5129,17 @@ assertInputField(schema.getQueryType()); // throws an error
-#### assertListType() +#### isListType() -Returns the value as a GraphQLList, or throws if it is not one. +
+ +
Overload 1
+ +Returns true when the value is a GraphQLList. **Signature:** - +
@@ -5144,7 +5156,7 @@ Returns the value as a GraphQLList, or throws if it is not one. type - + The GraphQL type to inspect. @@ -5163,8 +5175,8 @@ Returns the value as a GraphQLList, or throws if it is not one. - - The value typed as a GraphQLList. + + True when the value is a GraphQLList. @@ -5174,23 +5186,31 @@ Returns the value as a GraphQLList, or throws if it is not one.
Example
```ts -import { GraphQLList, GraphQLString, assertListType } from 'graphql/type'; +import { buildSchema } from 'graphql/utilities'; +import { GraphQLList, GraphQLString, isListType } from 'graphql/type'; -const listType = assertListType(new GraphQLList(GraphQLString)); +const schema = buildSchema(` + type Query { + tags: [String!]! + } +`); -listType.ofType; // => GraphQLString -assertListType(GraphQLString); // throws an error +const tagsField = schema.getQueryType()?.getFields().tags; + +isListType(new GraphQLList(GraphQLString)); // => true +isListType(GraphQLString); // => false +isListType(tagsField?.type); // => false ``` -
+
-#### assertNonNullType() +
Overload 2
-Returns the value as a GraphQLNonNull, or throws if it is not one. +Returns true when the output type is a GraphQLList. **Signature:** - +
@@ -5207,8 +5227,8 @@ Returns the value as a GraphQLNonNull, or throws if it is not one. type - - The GraphQL type to inspect. + + The GraphQL output type to inspect. @@ -5226,8 +5246,8 @@ Returns the value as a GraphQLNonNull, or throws if it is not one. - - The value typed as a GraphQLNonNull. + + True when the output type is a list type. @@ -5237,23 +5257,30 @@ Returns the value as a GraphQLNonNull, or throws if it is not one.
Example
```ts -import { GraphQLNonNull, GraphQLString, assertNonNullType } from 'graphql/type'; +import { buildSchema } from 'graphql/utilities'; +import { getNullableType, isListType } from 'graphql/type'; -const nonNullType = assertNonNullType(new GraphQLNonNull(GraphQLString)); +const schema = buildSchema(` + type Query { + tags: [String!]! + } +`); -nonNullType.ofType; // => GraphQLString -assertNonNullType(GraphQLString); // throws an error +const tagsField = schema.getQueryType()?.getFields().tags; +const nullableTagsType = getNullableType(tagsField?.type); + +isListType(nullableTagsType); // => true ``` -
+
-#### isInputType() +
Overload 3
-Returns true when the value can be used as a GraphQL input type. +Returns true when the value is a GraphQLList. **Signature:** - +
@@ -5271,7 +5298,7 @@ Returns true when the value can be used as a GraphQL input type. type - The GraphQL type to inspect. + The value to inspect. @@ -5289,8 +5316,8 @@ Returns true when the value can be used as a GraphQL input type. - - True when the value can be used as a GraphQL input type. + + True when the value is a list type. @@ -5300,36 +5327,21 @@ Returns true when the value can be used as a GraphQL input type.
Example
```ts -import { buildSchema } from 'graphql/utilities'; -import { isInputType } from 'graphql/type'; - -const schema = buildSchema(` - input ReviewInput { - stars: Int! - } - - type Review { - stars: Int! - } - - type Query { - review(input: ReviewInput): Review - } -`); +import { isListType } from 'graphql/type'; -isInputType(schema.getType('ReviewInput')); // => true -isInputType(schema.getType('Review')); // => false +isListType('[String]'); // => false +isListType(null); // => false ```
-#### assertInputType() +#### assertListType() -Returns the value as a GraphQL input type, or throws if it is not one. +Returns the value as a GraphQLList, or throws if it is not one. **Signature:** - +
@@ -5365,8 +5377,8 @@ Returns the value as a GraphQL input type, or throws if it is not one. - - The value typed as a GraphQL input type. + + The value typed as a GraphQLList. @@ -5376,38 +5388,27 @@ Returns the value as a GraphQL input type, or throws if it is not one.
Example
```ts -import { buildSchema } from 'graphql/utilities'; -import { assertInputType } from 'graphql/type'; - -const schema = buildSchema(` - input ReviewInput { - stars: Int! - } - - type Review { - stars: Int! - } - - type Query { - review(input: ReviewInput): Review - } -`); +import { GraphQLList, GraphQLString, assertListType } from 'graphql/type'; -const inputType = assertInputType(schema.getType('ReviewInput')); +const listType = assertListType(new GraphQLList(GraphQLString)); -inputType.toString(); // => 'ReviewInput' -assertInputType(schema.getType('Review')); // throws an error +listType.ofType; // => GraphQLString +assertListType(GraphQLString); // throws an error ```
-#### isOutputType() +#### isNonNullType() -Returns true when the value can be used as a GraphQL output type. +
+ +
Overload 1
+ +Returns true when the value is a GraphQLNonNull. **Signature:** - +
@@ -5424,7 +5425,7 @@ Returns true when the value can be used as a GraphQL output type. type - + The GraphQL type to inspect. @@ -5443,8 +5444,8 @@ Returns true when the value can be used as a GraphQL output type. - - True when the value can be used as a GraphQL output type. + + True when the value is a GraphQLNonNull. @@ -5455,35 +5456,31 @@ Returns true when the value can be used as a GraphQL output type. ```ts import { buildSchema } from 'graphql/utilities'; -import { isOutputType } from 'graphql/type'; +import { GraphQLNonNull, GraphQLString, isNonNullType } from 'graphql/type'; const schema = buildSchema(` - input ReviewInput { - stars: Int! - } - - type Review { - stars: Int! - } - type Query { - review(input: ReviewInput): Review + name: String! + nickname: String } `); -isOutputType(schema.getType('Review')); // => true -isOutputType(schema.getType('ReviewInput')); // => false +const fields = schema.getQueryType()?.getFields(); + +isNonNullType(new GraphQLNonNull(GraphQLString)); // => true +isNonNullType(fields?.name.type); // => true +isNonNullType(fields?.nickname.type); // => false ``` -
+
-#### assertOutputType() +
Overload 2
-Returns the value as a GraphQL output type, or throws if it is not one. +Returns true when the output type is a GraphQLNonNull. **Signature:** - +
@@ -5500,8 +5497,8 @@ Returns the value as a GraphQL output type, or throws if it is not one. type - - The GraphQL type to inspect. + + The GraphQL output type to inspect. @@ -5519,8 +5516,8 @@ Returns the value as a GraphQL output type, or throws if it is not one. - - The value typed as a GraphQL output type. + + True when the output type is a non-null type. @@ -5531,37 +5528,30 @@ Returns the value as a GraphQL output type, or throws if it is not one. ```ts import { buildSchema } from 'graphql/utilities'; -import { assertOutputType } from 'graphql/type'; +import { isNonNullType } from 'graphql/type'; const schema = buildSchema(` - input ReviewInput { - stars: Int! - } - - type Review { - stars: Int! - } - type Query { - review(input: ReviewInput): Review + name: String! + nickname: String } `); -const outputType = assertOutputType(schema.getType('Review')); +const fields = schema.getQueryType()?.getFields(); -outputType.toString(); // => 'Review' -assertOutputType(schema.getType('ReviewInput')); // throws an error +isNonNullType(fields?.name.type); // => true +isNonNullType(fields?.nickname.type); // => false ``` -
+
-#### isLeafType() +
Overload 3
-Returns true when the value is a GraphQL scalar or enum type. +Returns true when the value is a GraphQLNonNull. **Signature:** - +
@@ -5579,7 +5569,7 @@ Returns true when the value is a GraphQL scalar or enum type. type - The GraphQL type to inspect. + The value to inspect. @@ -5597,8 +5587,8 @@ Returns true when the value is a GraphQL scalar or enum type. - - True when the value is a GraphQL scalar or enum type. + + True when the value is a non-null type. @@ -5608,38 +5598,21 @@ Returns true when the value is a GraphQL scalar or enum type.
Example
```ts -import { buildSchema } from 'graphql/utilities'; -import { isLeafType } from 'graphql/type'; - -const schema = buildSchema(` - enum Episode { - NEW_HOPE - } - - type Review { - stars: Int! - } +import { isNonNullType } from 'graphql/type'; - type Query { - episode: Episode - review: Review - } -`); - -isLeafType(schema.getType('Episode')); // => true -isLeafType(schema.getType('String')); // => true -isLeafType(schema.getType('Review')); // => false +isNonNullType('String!'); // => false +isNonNullType(null); // => false ```
-#### assertLeafType() +#### assertNonNullType() -Returns the value as a GraphQL leaf type, or throws if it is not one. +Returns the value as a GraphQLNonNull, or throws if it is not one. **Signature:** - +
@@ -5675,8 +5648,8 @@ Returns the value as a GraphQL leaf type, or throws if it is not one. - - The value typed as a GraphQL leaf type. + + The value typed as a GraphQLNonNull. @@ -5686,39 +5659,23 @@ Returns the value as a GraphQL leaf type, or throws if it is not one.
Example
```ts -import { buildSchema } from 'graphql/utilities'; -import { assertLeafType } from 'graphql/type'; - -const schema = buildSchema(` - enum Episode { - NEW_HOPE - } - - type Review { - stars: Int! - } - - type Query { - episode: Episode - review: Review - } -`); +import { GraphQLNonNull, GraphQLString, assertNonNullType } from 'graphql/type'; -const episodeType = assertLeafType(schema.getType('Episode')); +const nonNullType = assertNonNullType(new GraphQLNonNull(GraphQLString)); -episodeType.toString(); // => 'Episode' -assertLeafType(schema.getType('Review')); // throws an error +nonNullType.ofType; // => GraphQLString +assertNonNullType(GraphQLString); // throws an error ```
-#### isCompositeType() +#### isInputType() -Returns true when the value is a GraphQL object, interface, or union type. +Returns true when the value can be used as a GraphQL input type. **Signature:** - +
@@ -5754,8 +5711,8 @@ Returns true when the value is a GraphQL object, interface, or union type. - - True when the value is a GraphQL object, interface, or union type. + + True when the value can be used as a GraphQL input type. @@ -5766,40 +5723,35 @@ Returns true when the value is a GraphQL object, interface, or union type. ```ts import { buildSchema } from 'graphql/utilities'; -import { isCompositeType } from 'graphql/type'; +import { isInputType } from 'graphql/type'; const schema = buildSchema(` - interface Node { - id: ID! + input ReviewInput { + stars: Int! } - type User implements Node { - id: ID! + type Review { + stars: Int! } - union SearchResult = User - type Query { - node: Node - search: [SearchResult] + review(input: ReviewInput): Review } `); -isCompositeType(schema.getType('User')); // => true -isCompositeType(schema.getType('Node')); // => true -isCompositeType(schema.getType('SearchResult')); // => true -isCompositeType(schema.getType('String')); // => false +isInputType(schema.getType('ReviewInput')); // => true +isInputType(schema.getType('Review')); // => false ```
-#### assertCompositeType() +#### assertInputType() -Returns the value as a GraphQL composite type, or throws if it is not one. +Returns the value as a GraphQL input type, or throws if it is not one. **Signature:** - +
@@ -5835,8 +5787,8 @@ Returns the value as a GraphQL composite type, or throws if it is not one. - - The value typed as a GraphQL composite type. + + The value typed as a GraphQL input type. @@ -5847,37 +5799,993 @@ Returns the value as a GraphQL composite type, or throws if it is not one. ```ts import { buildSchema } from 'graphql/utilities'; -import { assertCompositeType } from 'graphql/type'; +import { assertInputType } from 'graphql/type'; const schema = buildSchema(` - interface Node { - id: ID! + input ReviewInput { + stars: Int! } - type User implements Node { - id: ID! + type Review { + stars: Int! } type Query { - node: Node + review(input: ReviewInput): Review } `); -const userType = assertCompositeType(schema.getType('User')); +const inputType = assertInputType(schema.getType('ReviewInput')); -userType.toString(); // => 'User' -assertCompositeType(schema.getType('String')); // throws an error +inputType.toString(); // => 'ReviewInput' +assertInputType(schema.getType('Review')); // throws an error +``` + +
+ +#### isOutputType() + +Returns true when the value can be used as a GraphQL output type. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
True when the value can be used as a GraphQL output type.
+ +
+ +
Example
+ +```ts +import { buildSchema } from 'graphql/utilities'; +import { isOutputType } from 'graphql/type'; + +const schema = buildSchema(` + input ReviewInput { + stars: Int! + } + + type Review { + stars: Int! + } + + type Query { + review(input: ReviewInput): Review + } +`); + +isOutputType(schema.getType('Review')); // => true +isOutputType(schema.getType('ReviewInput')); // => false +``` + +
+ +#### assertOutputType() + +Returns the value as a GraphQL output type, or throws if it is not one. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The value typed as a GraphQL output type.
+ +
+ +
Example
+ +```ts +import { buildSchema } from 'graphql/utilities'; +import { assertOutputType } from 'graphql/type'; + +const schema = buildSchema(` + input ReviewInput { + stars: Int! + } + + type Review { + stars: Int! + } + + type Query { + review(input: ReviewInput): Review + } +`); + +const outputType = assertOutputType(schema.getType('Review')); + +outputType.toString(); // => 'Review' +assertOutputType(schema.getType('ReviewInput')); // throws an error +``` + +
+ +#### isLeafType() + +Returns true when the value is a GraphQL scalar or enum type. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
True when the value is a GraphQL scalar or enum type.
+ +
+ +
Example
+ +```ts +import { buildSchema } from 'graphql/utilities'; +import { isLeafType } from 'graphql/type'; + +const schema = buildSchema(` + enum Episode { + NEW_HOPE + } + + type Review { + stars: Int! + } + + type Query { + episode: Episode + review: Review + } +`); + +isLeafType(schema.getType('Episode')); // => true +isLeafType(schema.getType('String')); // => true +isLeafType(schema.getType('Review')); // => false ```
-#### isAbstractType() +#### assertLeafType() + +Returns the value as a GraphQL leaf type, or throws if it is not one. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The value typed as a GraphQL leaf type.
+ +
+ +
Example
+ +```ts +import { buildSchema } from 'graphql/utilities'; +import { assertLeafType } from 'graphql/type'; + +const schema = buildSchema(` + enum Episode { + NEW_HOPE + } + + type Review { + stars: Int! + } + + type Query { + episode: Episode + review: Review + } +`); + +const episodeType = assertLeafType(schema.getType('Episode')); + +episodeType.toString(); // => 'Episode' +assertLeafType(schema.getType('Review')); // throws an error +``` + +
+ +#### isCompositeType() + +Returns true when the value is a GraphQL object, interface, or union type. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
True when the value is a GraphQL object, interface, or union type.
+ +
+ +
Example
+ +```ts +import { buildSchema } from 'graphql/utilities'; +import { isCompositeType } from 'graphql/type'; + +const schema = buildSchema(` + interface Node { + id: ID! + } + + type User implements Node { + id: ID! + } + + union SearchResult = User + + type Query { + node: Node + search: [SearchResult] + } +`); + +isCompositeType(schema.getType('User')); // => true +isCompositeType(schema.getType('Node')); // => true +isCompositeType(schema.getType('SearchResult')); // => true +isCompositeType(schema.getType('String')); // => false +``` + +
+ +#### assertCompositeType() + +Returns the value as a GraphQL composite type, or throws if it is not one. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The value typed as a GraphQL composite type.
+ +
+ +
Example
+ +```ts +import { buildSchema } from 'graphql/utilities'; +import { assertCompositeType } from 'graphql/type'; + +const schema = buildSchema(` + interface Node { + id: ID! + } + + type User implements Node { + id: ID! + } + + type Query { + node: Node + } +`); + +const userType = assertCompositeType(schema.getType('User')); + +userType.toString(); // => 'User' +assertCompositeType(schema.getType('String')); // throws an error +``` + +
+ +#### isAbstractType() + +Returns true when the value is a GraphQL interface or union type. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
True when the value is a GraphQL interface or union type.
+ +
+ +
Example
+ +```ts +import { buildSchema } from 'graphql/utilities'; +import { isAbstractType } from 'graphql/type'; + +const schema = buildSchema(` + interface Node { + id: ID! + } + + type User implements Node { + id: ID! + } + + union SearchResult = User + + type Query { + node: Node + search: [SearchResult] + } +`); + +isAbstractType(schema.getType('Node')); // => true +isAbstractType(schema.getType('SearchResult')); // => true +isAbstractType(schema.getType('User')); // => false +``` + +
+ +#### assertAbstractType() + +Returns the value as a GraphQL abstract type, or throws if it is not one. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The value typed as a GraphQL abstract type.
+ +
+ +
Example
+ +```ts +import { buildSchema } from 'graphql/utilities'; +import { assertAbstractType } from 'graphql/type'; + +const schema = buildSchema(` + interface Node { + id: ID! + } + + type User implements Node { + id: ID! + } + + type Query { + node: Node + } +`); + +const nodeType = assertAbstractType(schema.getType('Node')); + +nodeType.toString(); // => 'Node' +assertAbstractType(schema.getType('User')); // throws an error +``` + +
+ +#### isWrappingType() + +Returns true when the value is a GraphQL list or non-null wrapper type. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
True when the value is a GraphQL list or non-null wrapper type.
+ +
+ +
Example
+ +```ts +import { + GraphQLList, + GraphQLNonNull, + GraphQLString, + isWrappingType, +} from 'graphql/type'; + +isWrappingType(new GraphQLList(GraphQLString)); // => true +isWrappingType(new GraphQLNonNull(GraphQLString)); // => true +isWrappingType(GraphQLString); // => false +``` + +
+ +#### assertWrappingType() + +Returns the value as a GraphQL wrapping type, or throws if it is not one. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The value typed as a GraphQL wrapping type.
+ +
+ +
Example
+ +```ts +import { GraphQLList, GraphQLString, assertWrappingType } from 'graphql/type'; + +const wrappingType = assertWrappingType(new GraphQLList(GraphQLString)); + +wrappingType.toString(); // => '[String]' +assertWrappingType(GraphQLString); // throws an error +``` + +
+ +#### isNullableType() + +Returns true when the value is a GraphQL type that can accept null. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
True when the value is a GraphQL type that can accept null.
+ +
+ +
Example
+ +```ts +import { GraphQLNonNull, GraphQLString, isNullableType } from 'graphql/type'; + +isNullableType(GraphQLString); // => true +isNullableType(new GraphQLNonNull(GraphQLString)); // => false +isNullableType(null); // => false +``` + +
+ +#### assertNullableType() + +Returns the value as a nullable GraphQL type, or throws if it is not one. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The value typed as a nullable GraphQL type.
+ +
+ +
Example
+ +```ts +import { + GraphQLNonNull, + GraphQLString, + assertNullableType, +} from 'graphql/type'; + +const nullableType = assertNullableType(GraphQLString); + +nullableType; // => GraphQLString +assertNullableType(new GraphQLNonNull(GraphQLString)); // throws an error +``` + +
+ +#### getNullableType() + +
+ +
Overload 1
+ +Returns the nullable type. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL type to inspect.
+ +
+ +
Example
+ +```ts +import { getNullableType } from 'graphql/type'; + +getNullableType(null); // => undefined +getNullableType(undefined); // => undefined +``` + +
+ +
Overload 2
+ +Returns the nullable type after removing one non-null wrapper. + +
+ +
Type Parameters
-Returns true when the value is a GraphQL interface or union type. + + + + + + + + + + + + + + + + + +
NameConstraintDefaultDescription
TThe nullable GraphQL type returned after removing one non-null wrapper.
**Signature:** - +
@@ -5894,8 +6802,8 @@ Returns true when the value is a GraphQL interface or union type. type - - The GraphQL type to inspect. + + A nullable type or non-null wrapper. @@ -5913,8 +6821,8 @@ Returns true when the value is a GraphQL interface or union type. - - True when the value is a GraphQL interface or union type. + + The nullable type after removing one non-null wrapper, if present. @@ -5924,40 +6832,29 @@ Returns true when the value is a GraphQL interface or union type.
Example
```ts -import { buildSchema } from 'graphql/utilities'; -import { isAbstractType } from 'graphql/type'; - -const schema = buildSchema(` - interface Node { - id: ID! - } - - type User implements Node { - id: ID! - } - - union SearchResult = User +import { + GraphQLList, + GraphQLNonNull, + GraphQLString, + getNullableType, +} from 'graphql/type'; - type Query { - node: Node - search: [SearchResult] - } -`); +const requiredString = new GraphQLNonNull(GraphQLString); +const stringList = new GraphQLList(GraphQLString); -isAbstractType(schema.getType('Node')); // => true -isAbstractType(schema.getType('SearchResult')); // => true -isAbstractType(schema.getType('User')); // => false +getNullableType(requiredString); // => GraphQLString +getNullableType(stringList); // => stringList ``` -
+
-#### assertAbstractType() +
Overload 3
-Returns the value as a GraphQL abstract type, or throws if it is not one. +Returns the nullable type after removing one non-null wrapper. **Signature:** - +
@@ -5974,7 +6871,7 @@ Returns the value as a GraphQL abstract type, or throws if it is not one. type - + The GraphQL type to inspect. @@ -5993,8 +6890,8 @@ Returns the value as a GraphQL abstract type, or throws if it is not one. - - The value typed as a GraphQL abstract type. + + The nullable type after removing one non-null wrapper, if present. @@ -6004,38 +6901,30 @@ Returns the value as a GraphQL abstract type, or throws if it is not one.
Example
```ts -import { buildSchema } from 'graphql/utilities'; -import { assertAbstractType } from 'graphql/type'; - -const schema = buildSchema(` - interface Node { - id: ID! - } - - type User implements Node { - id: ID! - } - - type Query { - node: Node - } -`); +import { + GraphQLList, + GraphQLNonNull, + GraphQLString, + getNullableType, +} from 'graphql/type'; -const nodeType = assertAbstractType(schema.getType('Node')); +const requiredStringList = new GraphQLNonNull( + new GraphQLList(GraphQLString), +); -nodeType.toString(); // => 'Node' -assertAbstractType(schema.getType('User')); // throws an error +getNullableType(requiredStringList).toString(); // => '[String]' +getNullableType(GraphQLString); // => GraphQLString ```
-#### isWrappingType() +#### isNamedType() -Returns true when the value is a GraphQL list or non-null wrapper type. +Returns true when the value is a GraphQL named type. **Signature:** - +
@@ -6071,8 +6960,8 @@ Returns true when the value is a GraphQL list or non-null wrapper type. - - True when the value is a GraphQL list or non-null wrapper type. + + True when the value is a GraphQL named type. @@ -6082,27 +6971,22 @@ Returns true when the value is a GraphQL list or non-null wrapper type.
Example
```ts -import { - GraphQLList, - GraphQLNonNull, - GraphQLString, - isWrappingType, -} from 'graphql/type'; +import { GraphQLList, GraphQLString, isNamedType } from 'graphql/type'; -isWrappingType(new GraphQLList(GraphQLString)); // => true -isWrappingType(new GraphQLNonNull(GraphQLString)); // => true -isWrappingType(GraphQLString); // => false +isNamedType(GraphQLString); // => true +isNamedType(new GraphQLList(GraphQLString)); // => false +isNamedType(null); // => false ```
-#### assertWrappingType() +#### assertNamedType() -Returns the value as a GraphQL wrapping type, or throws if it is not one. +Returns the value as a GraphQL named type, or throws if it is not one. **Signature:** - +
@@ -6138,8 +7022,8 @@ Returns the value as a GraphQL wrapping type, or throws if it is not one. - - The value typed as a GraphQL wrapping type. + + The value typed as a GraphQL named type. @@ -6149,23 +7033,27 @@ Returns the value as a GraphQL wrapping type, or throws if it is not one.
Example
```ts -import { GraphQLList, GraphQLString, assertWrappingType } from 'graphql/type'; +import { GraphQLList, GraphQLString, assertNamedType } from 'graphql/type'; -const wrappingType = assertWrappingType(new GraphQLList(GraphQLString)); +const namedType = assertNamedType(GraphQLString); -wrappingType.toString(); // => '[String]' -assertWrappingType(GraphQLString); // throws an error +namedType.name; // => 'String' +assertNamedType(new GraphQLList(GraphQLString)); // throws an error ```
-#### isNullableType() +#### getNamedType() -Returns true when the value is a GraphQL type that can accept null. +
+ +
Overload 1
+ +Returns the named type. **Signature:** - +
@@ -6182,7 +7070,7 @@ Returns true when the value is a GraphQL type that can accept null. type - + The GraphQL type to inspect. @@ -6190,6 +7078,48 @@ Returns true when the value is a GraphQL type that can accept null.
+
Example
+ +```ts +import { getNamedType } from 'graphql/type'; + +getNamedType(null); // => undefined +getNamedType(undefined); // => undefined +``` + +
+ +
Overload 2
+ +Returns the named input type after unwrapping all list and non-null wrappers. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + +
NameTypeDescription
typeThe GraphQL input type to inspect.
+ +
+
Returns
@@ -6201,8 +7131,8 @@ Returns true when the value is a GraphQL type that can accept null. - - + +
True when the value is a GraphQL type that can accept null.The named input type after unwrapping all wrappers.
@@ -6212,22 +7142,33 @@ Returns true when the value is a GraphQL type that can accept null.
Example
```ts -import { GraphQLNonNull, GraphQLString, isNullableType } from 'graphql/type'; +import { buildSchema } from 'graphql/utilities'; +import { getNamedType } from 'graphql/type'; -isNullableType(GraphQLString); // => true -isNullableType(new GraphQLNonNull(GraphQLString)); // => false -isNullableType(null); // => false +const schema = buildSchema(` + input ReviewInput { + stars: Int! + } + + type Query { + review(input: [ReviewInput!]!): Boolean + } +`); + +const inputArg = schema.getQueryType()?.getFields().review.args[0]; + +getNamedType(inputArg?.type).toString(); // => 'ReviewInput' ``` -
+
-#### assertNullableType() +
Overload 3
-Returns the value as a nullable GraphQL type, or throws if it is not one. +Returns the named output type after unwrapping all list and non-null wrappers. **Signature:** - +
@@ -6244,8 +7185,8 @@ Returns the value as a nullable GraphQL type, or throws if it is not one. type - - The GraphQL type to inspect. + + The GraphQL output type to inspect. @@ -6263,8 +7204,8 @@ Returns the value as a nullable GraphQL type, or throws if it is not one. - - The value typed as a nullable GraphQL type. + + The named output type after unwrapping all wrappers. @@ -6274,27 +7215,33 @@ Returns the value as a nullable GraphQL type, or throws if it is not one.
Example
```ts -import { - GraphQLNonNull, - GraphQLString, - assertNullableType, -} from 'graphql/type'; +import { buildSchema } from 'graphql/utilities'; +import { getNamedType } from 'graphql/type'; -const nullableType = assertNullableType(GraphQLString); +const schema = buildSchema(` + type User { + name: String + } -nullableType; // => GraphQLString -assertNullableType(new GraphQLNonNull(GraphQLString)); // throws an error + type Query { + users: [User!]! + } +`); + +const usersField = schema.getQueryType()?.getFields().users; + +getNamedType(usersField?.type).toString(); // => 'User' ``` -
+
-#### isNamedType() +
Overload 4
-Returns true when the value is a GraphQL named type. +Returns the named type after unwrapping all list and non-null wrappers. **Signature:** - +
@@ -6311,7 +7258,7 @@ Returns true when the value is a GraphQL named type. type - + The GraphQL type to inspect. @@ -6330,8 +7277,8 @@ Returns true when the value is a GraphQL named type. - - True when the value is a GraphQL named type. + + The named type after unwrapping all wrappers. @@ -6341,22 +7288,29 @@ Returns true when the value is a GraphQL named type.
Example
```ts -import { GraphQLList, GraphQLString, isNamedType } from 'graphql/type'; +import { + GraphQLList, + GraphQLNonNull, + GraphQLString, + getNamedType, +} from 'graphql/type'; -isNamedType(GraphQLString); // => true -isNamedType(new GraphQLList(GraphQLString)); // => false -isNamedType(null); // => false +const nestedType = new GraphQLNonNull( + new GraphQLList(new GraphQLNonNull(GraphQLString)), +); + +getNamedType(nestedType); // => GraphQLString ``` -
+
-#### assertNamedType() +
Overload 5
-Returns the value as a GraphQL named type, or throws if it is not one. +Returns the named type after unwrapping all list and non-null wrappers. **Signature:** - +
@@ -6373,7 +7327,7 @@ Returns the value as a GraphQL named type, or throws if it is not one. type - + The GraphQL type to inspect. @@ -6392,8 +7346,8 @@ Returns the value as a GraphQL named type, or throws if it is not one. - - The value typed as a GraphQL named type. + + The named type after unwrapping all wrappers, or undefined for nullish input. @@ -6403,12 +7357,14 @@ Returns the value as a GraphQL named type, or throws if it is not one.
Example
```ts -import { GraphQLList, GraphQLString, assertNamedType } from 'graphql/type'; - -const namedType = assertNamedType(GraphQLString); +import { + GraphQLList, + GraphQLString, + getNamedType, +} from 'graphql/type'; -namedType.name; // => 'String' -assertNamedType(new GraphQLList(GraphQLString)); // throws an error +getNamedType(new GraphQLList(GraphQLString)); // => GraphQLString +getNamedType(undefined); // => undefined ```
@@ -6932,7 +7888,7 @@ an object which can contain all the values you need.
-#### GraphQLScalarSerializer Deprecated +#### GraphQLScalarSerializer **Type alias.** Deprecated function type that serializes a runtime value as a scalar output value. Use [`GraphQLScalarOutputValueCoercer`](/api-v17/type#graphqlscalaroutputvaluecoercer) instead. @@ -6995,7 +7951,7 @@ value. Use [`GraphQLScalarOutputValueCoercer`](/api-v17/type#graphqlscalaroutput
-#### GraphQLScalarValueParser Deprecated +#### GraphQLScalarValueParser **Type alias.** Deprecated function type that parses a runtime input value as a scalar input value. Use [`GraphQLScalarInputValueCoercer`](/api-v17/type#graphqlscalarinputvaluecoercer) instead. @@ -7058,7 +8014,7 @@ value. Use [`GraphQLScalarInputValueCoercer`](/api-v17/type#graphqlscalarinputva
-#### GraphQLScalarLiteralParser Deprecated +#### GraphQLScalarLiteralParser **Type alias.** Deprecated function type that parses a GraphQL value literal as a scalar input value. Use [`GraphQLScalarInputLiteralCoercer`](/api-v17/type#graphqlscalarinputliteralcoercer) instead. @@ -7183,19 +8139,19 @@ input value. Use [`GraphQLScalarInputLiteralCoercer`](/api-v17/type#graphqlscala URL identifying the behavior specified for this custom scalar. - serialize? + serialize? Deprecated legacy serializer used to convert internal values for response
output. Use {"coerceOutputValue()"} instead. - parseValue? + parseValue? Deprecated legacy parser used to convert externally provided input values.
Use {"coerceInputValue()"} instead. - parseLiteral? + parseLiteral? Deprecated legacy parser used to convert externally provided input
literals. Use {"replaceVariables()"} and {"coerceInputLiteral()"} instead. @@ -7823,7 +8779,7 @@ an object which can contain all the values you need. The GraphQL type reference or runtime type for this element. - defaultValue? + defaultValue? Deprecated legacy default value for this argument. Use {"default"} instead. @@ -8164,7 +9120,7 @@ JSON.stringify(field); // => '"Query.greeting"' The GraphQL type reference or runtime type for this element. - defaultValue + defaultValue Deprecated legacy default value used when no explicit value is supplied.
Use {"default"} instead. @@ -9020,7 +9976,7 @@ an object which can contain all the values you need. The GraphQL type reference or runtime type for this element. - defaultValue? + defaultValue? Deprecated legacy default value for this input field. Use {"default"}
instead. @@ -9096,7 +10052,7 @@ instead. The GraphQL type reference or runtime type for this element. - defaultValue + defaultValue Deprecated legacy default value used when no explicit value is supplied.
Use {"default"} instead. diff --git a/website/pages/api-v17/utilities.mdx b/website/pages/api-v17/utilities.mdx index a8bac403d3..552bea9dce 100644 --- a/website/pages/api-v17/utilities.mdx +++ b/website/pages/api-v17/utilities.mdx @@ -1034,7 +1034,7 @@ fields; // => [{ name: 'greeting', parentType: 'Query', type: 'String' }]

Functions:
- astFromValue() + astFromValue() coerceInputValue() @@ -1042,11 +1042,13 @@ fields; // => [{ name: 'greeting', parentType: 'Query', type: 'String' }] replaceVariables() + typeFromAST() + validateInputValue() validateInputLiteral() - valueFromAST() + valueFromAST() valueFromASTUntyped() @@ -1056,7 +1058,7 @@ fields; // => [{ name: 'greeting', parentType: 'Query', type: 'String' }] ### Functions -#### astFromValue() Deprecated +#### astFromValue() Produces a GraphQL Value AST given a JavaScript object. Function will match JavaScript/JSON values to GraphQL AST schema format @@ -1474,6 +1476,314 @@ print(literal); // => '{ stars: 4 }'


+#### typeFromAST() + +
+ +
Overload 1
+ +Given a Schema and an AST node describing a type, return a GraphQLType +definition which applies to that type. For example, if provided the parsed +AST node for `[User]`, a GraphQLList instance will be returned, containing +the type called "User" found in the schema. If a type called "User" is not +found in the schema, then undefined will be returned. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
schemaGraphQL schema to use.
typeNodeThe GraphQL type AST node to resolve.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The GraphQL type referenced by the AST node, or undefined if it cannot be resolved.
+ +
+ +
Example
+ +```ts +import { parseType } from 'graphql/language'; +import { buildSchema, typeFromAST } from 'graphql/utilities'; + +const schema = buildSchema(` + type Query { + name: String + } +`); + +typeFromAST(schema, parseType('String'))?.toString(); // => 'String' +typeFromAST(schema, parseType('Missing')); // => undefined +``` + +
+ +
Overload 2
+ +Resolves a list type AST node against a schema. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
schemaGraphQL schema to use.
typeNodeThe list type AST node to resolve.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The GraphQL list type referenced by the AST node, or undefined if
+it cannot be resolved.
+ +
+ +
Example
+ +```ts +import { parseType } from 'graphql/language'; +import { buildSchema, typeFromAST } from 'graphql/utilities'; + +const schema = buildSchema(` + type Query { + tags: [String] + } +`); + +typeFromAST(schema, parseType('[String]'))?.toString(); // => '[String]' +typeFromAST(schema, parseType('[Missing]')); // => undefined +``` + +
+ +
Overload 3
+ +Resolves a non-null type AST node against a schema. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
schemaGraphQL schema to use.
typeNodeThe non-null type AST node to resolve.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The GraphQL non-null type referenced by the AST node, or undefined
+if it cannot be resolved.
+ +
+ +
Example
+ +```ts +import { parseType } from 'graphql/language'; +import { buildSchema, typeFromAST } from 'graphql/utilities'; + +const schema = buildSchema(` + type Query { + name: String! + } +`); + +typeFromAST(schema, parseType('String!'))?.toString(); // => 'String!' +typeFromAST(schema, parseType('[String!]!'))?.toString(); // => '[String!]!' +``` + +
+ +
Overload 4
+ +Resolves a type AST node against a schema. + +**Signature:** + + + +
+ +
Arguments
+ + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
schemaGraphQL schema to use.
typeNodeThe GraphQL type AST node to resolve.
+ +
+ +
Returns
+ + + + + + + + + + + + + + +
TypeDescription
The GraphQL type referenced by the AST node, or undefined if it
+cannot be resolved.
+ +
+ +
Example
+ +```ts +import { parseType } from 'graphql/language'; +import { buildSchema, typeFromAST } from 'graphql/utilities'; + +const schema = buildSchema(` + type User { + name: String + } + + type Query { + users: [User!]! + } +`); + +typeFromAST(schema, parseType('User'))?.toString(); // => 'User' +typeFromAST(schema, parseType('[User!]!'))?.toString(); // => '[User!]!' +typeFromAST(schema, parseType('Missing')); // => undefined +``` + +
+ #### validateInputValue() Validate that the provided input value is allowed for this type, collecting @@ -1707,7 +2017,7 @@ errors; // => []
-#### valueFromAST() Deprecated +#### valueFromAST() Produces a JavaScript value given a GraphQL Value AST. @@ -3928,9 +4238,9 @@ source; // => 'query Example{name}'

Functions:
- findBreakingChanges() + findBreakingChanges() - findDangerousChanges() + findDangerousChanges() findSchemaChanges()

@@ -3956,7 +4266,7 @@ source; // => 'query Example{name}' ### Functions -#### findBreakingChanges() Deprecated +#### findBreakingChanges() Given two schemas, returns an Array containing descriptions of all the types of breaking changes covered by the other functions down below. This @@ -4037,7 +4347,7 @@ changes.map((change) => change.type); // => ['FIELD_REMOVED']
-#### findDangerousChanges() Deprecated +#### findDangerousChanges() Given two schemas, returns an Array containing descriptions of all the types of potentially dangerous changes covered by the other functions down below.