graphql#DefinitionNode TypeScript Examples
The following examples show how to use
graphql#DefinitionNode.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: gql.ts From anchor-web-app with Apache License 2.0 | 6 votes |
export function findSelectionSet(document: DocumentNode): SelectionSetNode {
const query: DefinitionNode | undefined = document.definitions.find(
(definition) =>
definition.kind === 'OperationDefinition' &&
definition.operation === 'query',
);
if (!query) {
throw new Error(`Can't find "query" operation from query`);
}
return (query as OperationDefinitionNode).selectionSet;
}
Example #2
Source File: appsync-visitor.ts From amplify-codegen with Apache License 2.0 | 6 votes |
constructor(
protected _schema: GraphQLSchema,
rawConfig: TRawConfig,
additionalConfig: Partial<TPluginConfig>,
defaultScalars: NormalizedScalarsMap = DEFAULT_SCALARS,
) {
super(rawConfig, {
...additionalConfig,
scalars: buildScalars(_schema, rawConfig.scalars || '', defaultScalars),
target: rawConfig.target,
isTimestampFieldsAdded: rawConfig.isTimestampFieldsAdded,
handleListNullabilityTransparently: rawConfig.handleListNullabilityTransparently,
usePipelinedTransformer: rawConfig.usePipelinedTransformer,
transformerVersion: rawConfig.transformerVersion,
});
const typesUsedInDirectives: string[] = [];
if (rawConfig.directives) {
const directiveSchema = parse(rawConfig.directives);
directiveSchema.definitions.forEach((definition: DefinitionNode) => {
if (definition.kind === Kind.ENUM_TYPE_DEFINITION || definition.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION) {
typesUsedInDirectives.push(definition.name.value);
}
});
}
this.typesToSkip = [this._schema.getQueryType(), this._schema.getMutationType(), this._schema.getSubscriptionType()]
.filter(t => t)
.map(t => (t && t.name) || '');
this.typesToSkip.push(...typesUsedInDirectives);
}
Example #3
Source File: converter.ts From graphql-eslint with MIT License | 5 votes |
export function convertToESTree<T extends DocumentNode>(node: T, schema?: GraphQLSchema) {
const typeInfo = schema ? new TypeInfo(schema) : null;
const visitor: ASTVisitor = {
leave(node, key, parent) {
const leadingComments: Comment[] =
'description' in node && node.description
? [
{
type: node.description.block ? 'Block' : 'Line',
value: node.description.value,
},
]
: [];
const calculatedTypeInfo: TypeInformation | Record<string, never> = typeInfo
? {
argument: typeInfo.getArgument(),
defaultValue: typeInfo.getDefaultValue(),
directive: typeInfo.getDirective(),
enumValue: typeInfo.getEnumValue(),
fieldDef: typeInfo.getFieldDef(),
inputType: typeInfo.getInputType(),
parentInputType: typeInfo.getParentInputType(),
parentType: typeInfo.getParentType(),
gqlType: typeInfo.getType(),
}
: {};
const rawNode = () => {
if (parent && key !== undefined) {
return parent[key];
}
return node.kind === Kind.DOCUMENT
? <DocumentNode>{
...node,
definitions: node.definitions.map(definition =>
(definition as unknown as GraphQLESTreeNode<DefinitionNode>).rawNode()
),
}
: node;
};
const commonFields: Omit<GraphQLESTreeNode<typeof node>, 'parent'> = {
...node,
type: node.kind,
loc: convertLocation(node.loc),
range: [node.loc.start, node.loc.end],
leadingComments,
// Use function to prevent RangeError: Maximum call stack size exceeded
typeInfo: () => calculatedTypeInfo as any, // Don't know if can fix error
rawNode,
};
return 'type' in node
? {
...commonFields,
gqlType: node.type,
}
: commonFields;
},
};
return visit(node, typeInfo ? visitWithTypeInfo(typeInfo, visitor) : visitor) as GraphQLESTreeNode<T>;
}
Example #4
Source File: generate-query.test.ts From graphql-query-generator with MIT License | 5 votes |
function getOperationDefinition(doc: DocumentNode): OperationDefinitionNode {
const opDefs: DefinitionNode[] = doc.definitions.filter((def) => {
return def.kind === 'OperationDefinition'
})
return opDefs[0] as OperationDefinitionNode
}
Example #5
Source File: gqlTypes.ts From ra-data-prisma with MIT License | 5 votes |
document = (definitions: DefinitionNode[]): DocumentNode => ({
kind: Kind.DOCUMENT,
definitions,
})
Example #6
Source File: generate-query.ts From graphql-query-generator with MIT License | 4 votes |
function getSelectionSetAndVars(
schema: GraphQLSchema,
node: DefinitionNode,
config: InternalConfiguration,
depth: number = 0
): {
selectionSet: SelectionSetNode
variableDefinitionsMap: {
[variableName: string]: VariableDefinitionNode
}
variableValues: {
[variableName: string]: any
}
} {
let selections: SelectionNode[] = []
let variableDefinitionsMap: {
[variableName: string]: VariableDefinitionNode
} = {}
let variableValues: { [variableName: string]: any } = {}
// Abort at leaf nodes:
if (depth === config.maxDepth) {
return {
selectionSet: undefined,
variableDefinitionsMap,
variableValues
}
}
if (node.kind === Kind.OBJECT_TYPE_DEFINITION) {
let fields = getRandomFields(node.fields, config, schema, depth)
fields.forEach((field) => {
// Recurse, if field has children:
const nextNode = schema.getType(getTypeName(field.type)).astNode
let selectionSet: SelectionSetNode = undefined
if (typeof nextNode !== 'undefined') {
const res = getSelectionSetAndVars(schema, nextNode, config, depth + 1)
// Update counts and nodeFactor:
config.resolveCount += config.nodeFactor
config.nodeFactor *= getNextNodefactor(res.variableValues)
config.typeCount += config.nodeFactor
selectionSet = res.selectionSet
variableDefinitionsMap = {
...variableDefinitionsMap,
...res.variableDefinitionsMap
}
variableValues = { ...variableValues, ...res.variableValues }
}
const avs = getArgsAndVars(
field,
node.name.value,
config,
schema,
variableValues
)
variableDefinitionsMap = {
...variableDefinitionsMap,
...avs.variableDefinitionsMap
}
variableValues = { ...variableValues, ...avs.variableValues }
selections.push({
kind: Kind.FIELD,
name: getName(field.name.value),
selectionSet,
arguments: avs.args
})
})
} else if (node.kind === Kind.INTERFACE_TYPE_DEFINITION) {
let fields = getRandomFields(node.fields, config, schema, depth)
fields.forEach((field) => {
// Recurse, if field has children:
const nextNode = schema.getType(getTypeName(field.type)).astNode
let selectionSet: SelectionSetNode = undefined
if (typeof nextNode !== 'undefined') {
const res = getSelectionSetAndVars(schema, nextNode, config, depth + 1)
// Update counts and nodeFactor:
config.resolveCount += config.nodeFactor
config.nodeFactor *= getNextNodefactor(res.variableValues)
config.typeCount += config.nodeFactor
selectionSet = res.selectionSet
variableDefinitionsMap = {
...variableDefinitionsMap,
...res.variableDefinitionsMap
}
variableValues = { ...variableValues, ...res.variableValues }
}
const avs = getArgsAndVars(
field,
node.name.value,
config,
schema,
variableValues
)
variableDefinitionsMap = {
...variableDefinitionsMap,
...avs.variableDefinitionsMap
}
variableValues = { ...variableValues, ...avs.variableValues }
selections.push({
kind: Kind.FIELD,
name: getName(field.name.value),
selectionSet,
arguments: avs.args
})
})
// Get all objects that implement an interface
let objectsImplementingInterface = Object.values(
schema.getTypeMap()
).filter((namedType) => {
if (
namedType.astNode &&
namedType.astNode.kind === 'ObjectTypeDefinition'
) {
let interfaceNames = namedType.astNode.interfaces.map(
(interfaceNamedType) => {
return interfaceNamedType.name.value
}
)
if (interfaceNames.includes(node.name.value)) {
return true
}
}
return false
})
// Randomly select named types from the union
let pickObjectsImplementingInterface = objectsImplementingInterface.filter(
() => {
if (typeof config.breadthProbability === 'number') {
return random(config) <= config.breadthProbability
} else {
return random(config) <= config.breadthProbability(depth)
}
}
)
// If no named types are selected, select any one
if (pickObjectsImplementingInterface.length === 0) {
const forcedCleanIndex = Math.floor(
random(config) * objectsImplementingInterface.length
)
pickObjectsImplementingInterface.push(
objectsImplementingInterface[forcedCleanIndex]
)
}
pickObjectsImplementingInterface.forEach((namedType) => {
if (namedType.astNode) {
let type = namedType.astNode
// Unions can only contain objects
if (type.kind === Kind.OBJECT_TYPE_DEFINITION) {
// Get selections
let selectionSet: SelectionSetNode = undefined
const res = getSelectionSetAndVars(schema, type, config, depth)
selectionSet = res.selectionSet
variableDefinitionsMap = {
...variableDefinitionsMap,
...res.variableDefinitionsMap
}
variableValues = { ...variableValues, ...res.variableValues }
let fragment: InlineFragmentNode = {
kind: Kind.INLINE_FRAGMENT,
typeCondition: {
kind: Kind.NAMED_TYPE,
name: {
kind: Kind.NAME,
value: type.name.value
}
},
selectionSet: selectionSet
}
selections.push(fragment)
} else {
throw Error(
`There should only be object types ` +
`in the selectionSet but found: ` +
`"${JSON.stringify(type, null, 2)}"`
)
}
} else {
selections.push({
kind: Kind.FIELD,
name: {
kind: Kind.NAME,
value: namedType.name
}
})
}
})
} else if (node.kind === Kind.UNION_TYPE_DEFINITION) {
// Get the named types in the union
let unionNamedTypes = node.types.map((namedTypeNode) => {
return schema.getType(namedTypeNode.name.value)
})
// Randomly select named types from the union
let pickUnionNamedTypes = unionNamedTypes.filter(() => {
if (typeof config.breadthProbability === 'number') {
return random(config) <= config.breadthProbability
} else {
return random(config) <= config.breadthProbability(depth)
}
})
// If no named types are selected, select any one
if (pickUnionNamedTypes.length === 0) {
const forcedCleanIndex = Math.floor(
random(config) * unionNamedTypes.length
)
pickUnionNamedTypes.push(unionNamedTypes[forcedCleanIndex])
}
pickUnionNamedTypes.forEach((namedType) => {
if (namedType.astNode) {
let type = namedType.astNode
// Unions can only contain objects
if (type.kind === Kind.OBJECT_TYPE_DEFINITION) {
// Get selections
let selectionSet: SelectionSetNode = undefined
const res = getSelectionSetAndVars(schema, type, config, depth)
selectionSet = res.selectionSet
variableDefinitionsMap = {
...variableDefinitionsMap,
...res.variableDefinitionsMap
}
variableValues = { ...variableValues, ...res.variableValues }
let fragment: InlineFragmentNode = {
kind: Kind.INLINE_FRAGMENT,
typeCondition: {
kind: Kind.NAMED_TYPE,
name: {
kind: Kind.NAME,
value: type.name.value
}
},
selectionSet: selectionSet
}
selections.push(fragment)
} else {
throw Error(
`There should only be object types ` +
`in the selectionSet but found: ` +
`"${JSON.stringify(type, null, 2)}"`
)
}
} else {
selections.push({
kind: Kind.FIELD,
name: {
kind: Kind.NAME,
value: namedType.name
}
})
}
})
}
let aliasIndexes: { [fieldName: string]: number } = {}
let cleanselections: SelectionNode[] = []
// Ensure unique field names/aliases
selections.forEach((selectionNode) => {
if (selectionNode.kind === Kind.FIELD) {
let fieldName = selectionNode.name.value
if (fieldName in aliasIndexes) {
cleanselections.push({
...selectionNode,
...{
alias: {
kind: Kind.NAME,
value: `${fieldName}${aliasIndexes[fieldName]++}`
}
}
})
} else {
aliasIndexes[fieldName] = 2
cleanselections.push(selectionNode)
}
} else if (selectionNode.kind === Kind.INLINE_FRAGMENT) {
let cleanFragmentSelections: SelectionNode[] = []
selectionNode.selectionSet.selections.forEach((fragmentSelectionNode) => {
if (fragmentSelectionNode.kind === Kind.FIELD) {
let fieldName = fragmentSelectionNode.name.value
if (fieldName in aliasIndexes) {
cleanFragmentSelections.push({
...fragmentSelectionNode,
...{
alias: {
kind: Kind.NAME,
value: `${fieldName}${aliasIndexes[fieldName]++}`
}
}
})
} else {
aliasIndexes[fieldName] = 2
cleanFragmentSelections.push(fragmentSelectionNode)
}
}
})
selectionNode.selectionSet.selections = cleanFragmentSelections
cleanselections.push(selectionNode)
} else {
throw Error(
`There should not be any fragment spreads in the selectionNode "${JSON.stringify(
selectionNode,
null,
2
)}"`
)
}
})
return {
selectionSet:
cleanselections.length > 0
? {
kind: Kind.SELECTION_SET,
selections: cleanselections
}
: undefined,
variableDefinitionsMap,
variableValues
}
}