graphql#DocumentNode TypeScript Examples

The following examples show how to use graphql#DocumentNode. 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: utils.ts    From apollo-cache-policies with Apache License 2.0 7 votes vote down vote up
// Returns a query that can be used to watch a filtered list of normalized cache entities by converting the fragment to a query
// and dynamically adding a type policy that returns the list of matching entities.
export function buildWatchFragmentWhereQuery<FragmentType>(options: WatchFragmentWhereOptions<FragmentType> & {
  cache: InvalidationPolicyCache;
  policies: Policies;
  fieldName: string;
}): DocumentNode {
  const { fragment, filter, policies, cache, fieldName, } = options;
  const fragmentDefinition = fragment.definitions[0] as FragmentDefinitionNode;
  const __typename = fragmentDefinition.typeCondition.name.value;

  const query = _generateQueryFromFragment({
    fragmentDefinition,
    fieldName,
  });

  // @ts-ignore The getFieldPolicy is private but we need it here to determine
  // if the dynamic type policy we generate for the corresponding fragment has
  // already been added
  if (!policies.getFieldPolicy('Query', fieldName)) {
    policies.addTypePolicies({
      Query: {
        fields: {
          [fieldName]: {
            read(_existing) {
              return cache.readReferenceWhere({
                __typename,
                filter,
              });
            }
          }
        }
      }
    });
  }

  return query;
}
Example #2
Source File: GraphQLWrapper.ts    From connect with GNU Lesser General Public License v3.0 6 votes vote down vote up
// Make every operation type a query, until GraphQL subscriptions get added again.
function createRequest(query: DocumentNode, args: object): GraphQLRequest {
  if (query.definitions) {
    query = {
      ...query,
      definitions: query.definitions.map((definition) => ({
        ...definition,
        operation: 'query',
      })),
    }
  }
  return createRequestUrql(query, args)
}
Example #3
Source File: parseAndPrintWithCache.ts    From graphql-mesh with MIT License 6 votes vote down vote up
export function parseWithCache(sdl: string): DocumentNode {
  const trimmedSdl = sdl.trim();
  let document: DocumentNode = parseCache.get(trimmedSdl);
  if (!document) {
    document = parse(trimmedSdl, { noLocation: true });
    parseCache.set(trimmedSdl, document);
    printCache.set(JSON.stringify(document), trimmedSdl);
  }
  return document;
}
Example #4
Source File: GraphQLWrapper.ts    From connect with GNU Lesser General Public License v3.0 6 votes vote down vote up
subscribeToQuery(
    query: DocumentNode,
    args: any = {},
    callback: SubscriptionCallback<QueryResult>
  ): SubscriptionHandler {
    const request = createRequest(query, args)

    return pipe(
      this.#client.executeQuery(request, {
        pollInterval: this.#pollInterval,
        requestPolicy: 'cache-and-network',
      }),
      subscribe((result: QueryResult) => {
        if (this.#verbose) {
          console.log(this.describeQueryResult(result))
        }
        if (result.error) {
          callback(
            new Error(
              'Error performing subscription.\n' +
                `${result.error.name}: ${result.error.message} \n` +
                this.describeQueryResult(result)
            )
          )
          return
        }
        callback(null, result)
      })
    )
  }
Example #5
Source File: gql.ts    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
export function createDocumentNode(): DocumentNode {
  return {
    kind: 'Document',
    definitions: [
      {
        kind: 'OperationDefinition',
        operation: 'query',
        selectionSet: {
          kind: 'SelectionSet',
          selections: [],
        },
      },
    ],
  };
}
Example #6
Source File: loading.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
export function loadAndMergeQueryDocuments(inputPaths: string[], tagName: string = 'gql'): DocumentNode {
  const sources = inputPaths
    .map(inputPath => {
      const body = fs.readFileSync(inputPath, 'utf8');
      if (!body) {
        return null;
      }
      return new Source(body, inputPath);
    })
    .filter(source => source);

  return concatAST((sources as Source[]).map(source => parse(source)));
}
Example #7
Source File: index.ts    From fullstack-starterkit with MIT License 6 votes vote down vote up
private async graphqlRequest({ query, variables, context, operationName }: GraphQLRequest): Promise<any> {
    const queryNode: DocumentNode = allQueries[operationName];
    const queryNodeString: string = print(queryNode);
    const source: string = query || queryNodeString;

    const contextValue = (context = context ? { ...this.context, ...context } : this.context);
    const { data, errors } = await graphql({ schema, source, variableValues: variables, contextValue });

    if (errors && errors.length) {
      throw errors[0];
    }

    if (!data) {
      throw new Error(`Invalid query ${operationName}.`);
    }

    return data[operationName];
  }
Example #8
Source File: use.imerative.query.ts    From ui with GNU Affero General Public License v3.0 6 votes vote down vote up
useImperativeQuery: <TData, TVariables>(
  query: DocumentNode
) => (variables: TVariables) => Promise<ApolloQueryResult<TData>> = (query) => {
  const { refetch } = useQuery(query, { skip: true })

  return useCallback(
    (variables) => {
      return refetch(variables)
    },
    [refetch]
  )
}
Example #9
Source File: buildGqlQuery.ts    From ra-data-prisma with MIT License 6 votes vote down vote up
buildFieldsFromFragment = (
  fragment: DocumentNode | string,
  resourceName: string,
  fetchType: string,
): SelectionNode[] => {
  let parsedFragment = {};

  if (
    typeof fragment === "object" &&
    fragment.kind &&
    fragment.kind === "Document"
  ) {
    parsedFragment = fragment;
  }

  if (typeof fragment === "string") {
    if (!fragment.startsWith("fragment")) {
      fragment = `fragment tmp on ${resourceName} ${fragment}`;
    }

    try {
      parsedFragment = parse(fragment);
    } catch (e) {
      throw new Error(
        `Invalid fragment given for resource '${resourceName}' and fetchType '${fetchType}' (${e.message}).`,
      );
    }
  }

  return (parsedFragment as any).definitions?.[0].selectionSet.selections;
}
Example #10
Source File: graphql.ts    From platyplus with MIT License 6 votes vote down vote up
queryToSubscription = (query: DocumentNode): DocumentNode => {
  const result: typeof query = clone(query)
  result.definitions.forEach((definition) => {
    if (definition.kind === 'OperationDefinition') {
      ;(definition.operation as string) = 'subscription'
    }
  })
  return result
}
Example #11
Source File: useGetQueryDataByFieldName.ts    From apollo-cache-policies with Apache License 2.0 6 votes vote down vote up
useGetQueryDataByFieldName = <FieldType>(query: DocumentNode, fieldName: string) => {
  const result = useQuery<Record<string, FieldType>>(query, {
    fetchPolicy: 'cache-only',
  });

  const requiredDataResult = {
    ...result,
    data: result?.data?.[fieldName],
  };

  type RequiredDataResult = typeof requiredDataResult & { data: FieldType };
  return requiredDataResult as RequiredDataResult;
}
Example #12
Source File: graphql-js-validation.ts    From graphql-eslint with MIT License 6 votes vote down vote up
getFragmentDefsAndFragmentSpreads = (node: DocumentNode): GetFragmentDefsAndFragmentSpreads => {
  const fragmentDefs = new Set<string>();
  const fragmentSpreads = new Set<string>();

  const visitor: ASTVisitor = {
    FragmentDefinition(node) {
      fragmentDefs.add(node.name.value);
    },
    FragmentSpread(node) {
      fragmentSpreads.add(node.name.value);
    },
  };

  visit(node, visitor);
  return { fragmentDefs, fragmentSpreads };
}
Example #13
Source File: useFragmentWhere.ts    From apollo-cache-policies with Apache License 2.0 6 votes vote down vote up
// A hook for subscribing to a fragment for entities in the Apollo cache matching a given filter from a React component.
export default function useFragmentWhere<FragmentType>(fragment: DocumentNode, filter?: FragmentWhereFilter<FragmentType>) {
  const context = useContext(getApolloContext());
  const client = context.client;
  const cache = client?.cache as unknown as InvalidationPolicyCache;
  const fieldName = useFragmentTypePolicyFieldName();

  const query = useOnce(() => buildWatchFragmentWhereQuery({
    filter,
    fragment,
    fieldName,
    cache,
    policies: cache.policies,
  }));

  return useGetQueryDataByFieldName<FragmentType[]>(query, fieldName);
}
Example #14
Source File: cache.ts    From taskcafe with MIT License 6 votes vote down vote up
export function updateApolloCache<T>(
  client: DataProxy,
  document: DocumentNode,
  update: UpdateCacheFn<T>,
  variables?: any,
) {
  let queryArgs: DataProxy.Query<any, any>;
  if (variables) {
    queryArgs = {
      query: document,
      variables,
    };
  } else {
    queryArgs = {
      query: document,
    };
  }
  const cache: T | null = client.readQuery(queryArgs);
  if (cache) {
    const newCache = update(cache);
    client.writeQuery({
      ...queryArgs,
      data: newCache,
    });
  }
}
Example #15
Source File: gql.ts    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
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 #16
Source File: generate-query.d.ts    From graphql-query-generator with MIT License 6 votes vote down vote up
export declare function generateRandomQuery(schema: GraphQLSchema, config?: Configuration): {
    queryDocument: DocumentNode;
    variableValues: {
        [varName: string]: any;
    };
    seed: number;
    typeCount: number;
    resolveCount: number;
};
Example #17
Source File: graphql.tsx    From hakka with MIT License 5 votes vote down vote up
HideTopicDocument: DocumentNode = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"hideTopic"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"hide"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Boolean"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"hideTopic"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}},{"kind":"Argument","name":{"kind":"Name","value":"hide"},"value":{"kind":"Variable","name":{"kind":"Name","value":"hide"}}}]}]}}]}
Example #18
Source File: graphql-js-validation.ts    From graphql-eslint with MIT License 5 votes vote down vote up
function validateDocument(
  context: GraphQLESLintRuleContext,
  schema: GraphQLSchema | null = null,
  documentNode: DocumentNode,
  rule: ValidationRule
): void {
  if (documentNode.definitions.length === 0) {
    return;
  }
  try {
    const validationErrors = schema
      ? validate(schema, documentNode, [rule])
      : validateSDL(documentNode, null, [rule as any]);

    for (const error of validationErrors) {
      const { line, column } = error.locations[0];
      const sourceCode = context.getSourceCode();
      const { tokens } = sourceCode.ast;
      const token = tokens.find(token => token.loc.start.line === line && token.loc.start.column === column - 1);

      let loc: { line: number; column: number } | AST.SourceLocation = {
        line,
        column: column - 1,
      };
      if (token) {
        loc =
          // if cursor on `@` symbol than use next node
          (token.type as any) === '@' ? sourceCode.getNodeByRangeIndex(token.range[1] + 1).loc : token.loc;
      }

      context.report({
        loc,
        message: error.message,
      });
    }
  } catch (e) {
    context.report({
      loc: REPORT_ON_FIRST_CHARACTER,
      message: e.message,
    });
  }
}
Example #19
Source File: graphql.tsx    From hakka with MIT License 5 votes vote down vote up
LikeCommentDocument: DocumentNode = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"likeComment"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"commentId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"likeComment"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"commentId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"commentId"}}}]}]}}]}
Example #20
Source File: converter.ts    From graphql-eslint with MIT License 5 votes vote down vote up
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 #21
Source File: index.ts    From fullstack-starterkit with MIT License 5 votes vote down vote up
types: DocumentNode[] = [userTypes, postTypes]
Example #22
Source File: graphql.tsx    From hakka with MIT License 5 votes vote down vote up
CreateCommentDocument: DocumentNode = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"createComment"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"topicId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"content"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"parentId"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createComment"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"topicId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"topicId"}}},{"kind":"Argument","name":{"kind":"Name","value":"content"},"value":{"kind":"Variable","name":{"kind":"Name","value":"content"}}},{"kind":"Argument","name":{"kind":"Name","value":"parentId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"parentId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"html"}},{"kind":"Field","name":{"kind":"Name","value":"likesCount"}},{"kind":"Field","name":{"kind":"Name","value":"isLiked"}},{"kind":"Field","name":{"kind":"Name","value":"author"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"username"}},{"kind":"Field","name":{"kind":"Name","value":"avatar"}}]}},{"kind":"Field","name":{"kind":"Name","value":"parent"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"author"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"username"}}]}},{"kind":"Field","name":{"kind":"Name","value":"html"}}]}}]}}]}}]}
Example #23
Source File: index.ts    From graphql-mesh with MIT License 5 votes vote down vote up
async getNonExecutableSchemaForHTTPSource(
    httpSourceConfig: YamlConfig.GraphQLHandlerHTTPConfiguration
  ): Promise<GraphQLSchema> {
    const schemaHeadersFactory = getInterpolatedHeadersFactory(httpSourceConfig.schemaHeaders || {});
    const customFetch = await this.getCustomFetchImpl(httpSourceConfig.customFetch);
    if (httpSourceConfig.introspection) {
      const headers = schemaHeadersFactory({
        env: process.env,
      });
      const sdlOrIntrospection = await readFileOrUrl<string | IntrospectionQuery | DocumentNode>(
        httpSourceConfig.introspection,
        {
          cwd: this.baseDir,
          allowUnknownExtensions: true,
          fetch: customFetch,
          headers,
        }
      );
      if (typeof sdlOrIntrospection === 'string') {
        return buildSchema(sdlOrIntrospection);
      } else if (isDocumentNode(sdlOrIntrospection)) {
        return buildASTSchema(sdlOrIntrospection);
      } else if (sdlOrIntrospection.__schema) {
        return buildClientSchema(sdlOrIntrospection);
      }
      throw new Error(`Invalid introspection data: ${util.inspect(sdlOrIntrospection)}`);
    }
    return this.nonExecutableSchema.getWithSet(() => {
      const endpointFactory = getInterpolatedStringFactory(httpSourceConfig.endpoint);
      const executor = this.urlLoader.getExecutorAsync(httpSourceConfig.endpoint, {
        ...httpSourceConfig,
        customFetch,
        subscriptionsProtocol: httpSourceConfig.subscriptionsProtocol as SubscriptionProtocol,
      });
      return introspectSchema(function meshIntrospectionExecutor(params: ExecutionRequest) {
        const resolverData = getResolverData(params);
        return executor({
          ...params,
          extensions: {
            ...params.extensions,
            headers: schemaHeadersFactory(resolverData),
            endpoint: endpointFactory(resolverData),
          },
        });
      });
    });
  }
Example #24
Source File: schema.ts    From squid with GNU General Public License v3.0 5 votes vote down vote up
export function buildSchema(doc: DocumentNode): GraphQLSchema {
    let schema = extendSchema(baseSchema, doc)
    let errors = validateSchema(schema).filter(err => !/query root/i.test(err.message))
    if (errors.length > 0) {
        throw errors[0]
    }
    return schema
}
Example #25
Source File: get-mesh.ts    From graphql-mesh with MIT License 5 votes vote down vote up
memoizedGetOperationType = memoize1((document: DocumentNode) => {
  const operationAST = getOperationAST(document, undefined);
  if (!operationAST) {
    throw new Error('Must provide document with a valid operation');
  }
  return operationAST.operation;
})
Example #26
Source File: opencrud.ts    From squid with GNU General Public License v3.0 5 votes vote down vote up
export function buildServerSchema(model: Model, dialect: Dialect): DocumentNode {
    let scalars = ['ID'].concat(Object.keys(customScalars)).map(name => 'scalar ' + name).join('\n')
    let queries = generateOpenCrudQueries(model, dialect)
    return parse(scalars  + '\n\n' + queries)
}
Example #27
Source File: generate-query.test.ts    From graphql-query-generator with MIT License 5 votes vote down vote up
function getOperationDefinition(doc: DocumentNode): OperationDefinitionNode {
  const opDefs: DefinitionNode[] = doc.definitions.filter((def) => {
    return def.kind === 'OperationDefinition'
  })
  return opDefs[0] as OperationDefinitionNode
}
Example #28
Source File: GraphQLWrapper.ts    From connect with GNU Lesser General Public License v3.0 5 votes vote down vote up
async performQueryWithParser<T>(
    query: DocumentNode,
    args: any = {},
    parser: ParseFunction
  ): Promise<T> {
    const result = await this.performQuery(query, args)
    return this.parseQueryResult<T>(parser, result)
  }
Example #29
Source File: index.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
export function compileToIR(schema: GraphQLSchema, document: DocumentNode, options: CompilerOptions = {}): CompilerContext {
  if (options.addTypename) {
    document = withTypenameFieldAddedWhereNeeded(document);
  }

  const compiler = new Compiler(schema, options);

  const operations: { [operationName: string]: Operation } = Object.create(null);
  const fragments: { [fragmentName: string]: Fragment } = Object.create(null);

  for (const definition of document.definitions) {
    try {
      switch (definition.kind) {
        case Kind.OPERATION_DEFINITION:
          const operation = compiler.compileOperation(definition);
          operations[operation.operationName] = operation;
          break;
        case Kind.FRAGMENT_DEFINITION:
          const fragment = compiler.compileFragment(definition);
          fragments[fragment.fragmentName] = fragment;
          break;
      }
    } catch (e) {
      if (e instanceof GraphQLError) {
        if (definition.kind === 'OperationDefinition' && definition.name) {
          const locInfo = definition.name.loc ? `in ${definition.name.loc.source.name}` : '';
          console.log(`${e.message} but found ${definition.operation}: ${definition.name.value} ${locInfo}  `);
        } else {
          console.log(e.message);
        }
      }
    }
  }

  for (const fragmentSpread of compiler.unresolvedFragmentSpreads) {
    const fragment = fragments[fragmentSpread.fragmentName];
    if (!fragment) {
      throw new Error(`Cannot find fragment "${fragmentSpread.fragmentName}"`);
    }

    // Compute the intersection between the possible,types of the fragment spread and the fragment.
    const possibleTypes = fragment.selectionSet.possibleTypes.filter(type => fragmentSpread.selectionSet.possibleTypes.includes(type));

    fragmentSpread.isConditional = fragment.selectionSet.possibleTypes.some(
      type => !fragmentSpread.selectionSet.possibleTypes.includes(type),
    );

    fragmentSpread.selectionSet = {
      possibleTypes,
      selections: fragment.selectionSet.selections,
    };
  }

  const typesUsed = compiler.typesUsed;

  return { schema, typesUsed, operations, fragments, options };
}