graphql#ArgumentNode TypeScript Examples

The following examples show how to use graphql#ArgumentNode. 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: generate-query.ts    From graphql-query-generator with MIT License 6 votes vote down vote up
function getVariable(argName: string, varName: string): ArgumentNode {
  return {
    kind: Kind.ARGUMENT,
    loc,
    name: getName(argName),
    value: {
      kind: Kind.VARIABLE,
      name: getName(varName)
    }
  }
}
Example #2
Source File: generate-query.ts    From graphql-query-generator with MIT License 6 votes vote down vote up
/**
 * Given a listSize directive, get the slicingArguments argument
 */
function getSlicingArguments(listSizeDirective: DirectiveNode): ArgumentNode {
  if (!listSizeDirective) return undefined

  const slicingArgumentsArg = listSizeDirective.arguments.find(
    (arg) => arg.name.value === 'slicingArguments'
  )

  if (!slicingArgumentsArg || slicingArgumentsArg.value.kind !== 'ListValue')
    return undefined

  return slicingArgumentsArg
}
Example #3
Source File: generate-query.ts    From graphql-query-generator with MIT License 6 votes vote down vote up
/**
 * Given a listSize directive, get the requireOneSlicingArgument argument
 */
function getRequireOneSlicingArgument(
  listSizeDirective: DirectiveNode
): ArgumentNode {
  if (!listSizeDirective) return undefined

  const requireOneSlicingArg = listSizeDirective.arguments.find(
    (arg) => arg.name.value === 'requireOneSlicingArgument'
  )

  if (
    !requireOneSlicingArg ||
    requireOneSlicingArg.value.kind !== 'BooleanValue'
  )
    return undefined

  return requireOneSlicingArg
}
Example #4
Source File: buildGqlQuery.ts    From ra-data-prisma with MIT License 6 votes vote down vote up
buildArgs = (
  query: Query,
  variables: { [key: string]: any } = {},
) => {
  if (query.args.length === 0) {
    return [];
  }

  const validVariables = Object.keys(variables).filter(
    (k) => typeof variables[k] !== "undefined",
  );
  return query.args
    .filter((arg) => validVariables.includes(arg.name))
    .reduce(
      (acc: ArgumentNode[], arg) => [
        ...acc,
        gqlTypes.argument(
          gqlTypes.name(arg.name),
          gqlTypes.variable(gqlTypes.name(arg.name)),
        ),
      ],
      [] as ArgumentNode[],
    );
}
Example #5
Source File: require-deprecation-reason.ts    From graphql-eslint with MIT License 5 votes vote down vote up
rule: GraphQLESLintRule = {
  meta: {
    docs: {
      description: 'Require all deprecation directives to specify a reason.',
      category: 'Schema',
      url: 'https://github.com/B2o5T/graphql-eslint/blob/master/docs/rules/require-deprecation-reason.md',
      recommended: true,
      examples: [
        {
          title: 'Incorrect',
          code: /* GraphQL */ `
            type MyType {
              name: String @deprecated
            }
          `,
        },
        {
          title: 'Incorrect',
          code: /* GraphQL */ `
            type MyType {
              name: String @deprecated(reason: "")
            }
          `,
        },
        {
          title: 'Correct',
          code: /* GraphQL */ `
            type MyType {
              name: String @deprecated(reason: "no longer relevant, please use fullName field")
            }
          `,
        },
      ],
    },
    type: 'suggestion',
    schema: [],
  },
  create(context) {
    return {
      'Directive[name.value=deprecated]'(node: GraphQLESTreeNode<DirectiveNode>) {
        const reasonArgument = node.arguments.find(arg => arg.name.value === 'reason') as any as ArgumentNode;
        const value = reasonArgument && String(valueFromNode(reasonArgument.value)).trim();

        if (!value) {
          context.report({
            node: node.name,
            message: 'Directive "@deprecated" must have a reason!',
          });
        }
      },
    };
  },
}
Example #6
Source File: gqlTypes.ts    From ra-data-prisma with MIT License 5 votes vote down vote up
argument = (name: NameNode, value: ValueNode): ArgumentNode => ({
  kind: Kind.ARGUMENT,
  name,
  value,
})
Example #7
Source File: generate-query.ts    From graphql-query-generator with MIT License 4 votes vote down vote up
function getArgsAndVars(
  field: FieldDefinitionNode,
  nodeName: string,
  config: InternalConfiguration,
  schema: GraphQLSchema,
  providedValues: { [varName: string]: any }
): {
  args: ArgumentNode[]
  variableDefinitionsMap: { [varName: string]: VariableDefinitionNode }
  variableValues: { [varName: string]: any }
} {
  const fieldName = field.name.value
  const allArgs = field.arguments
  const args: ArgumentNode[] = []

  const variableDefinitionsMap: {
    [varName: string]: VariableDefinitionNode
  } = {}

  const requiredArguments = allArgs.filter((arg) =>
    considerArgument(arg, config)
  )

  /**
   * Check for slicing arguments defined in a @listSize directive that should
   * be present:
   */
  const missingSlicingArg = getMissingSlicingArg(
    requiredArguments,
    field,
    schema
  )

  /**
   * Check if missingSlicingArg is already in requiredArguments
   *
   * Because slicing arguments may be deeply nested (input object types), there
   * isn't a simple way to check for conflicts
   */
  if (
    missingSlicingArg &&
    !requiredArguments.find((arg) => {
      return arg.name.value === missingSlicingArg.name.value
    })
  ) {
    requiredArguments.push(missingSlicingArg)
  }

  requiredArguments.forEach((arg) => {
    const varName = `${nodeName}__${fieldName}__${arg.name.value}`
    args.push(getVariable(arg.name.value, varName))
    variableDefinitionsMap[varName] = getVariableDefinition(varName, arg.type)
  })

  const variableValues: { [varName: string]: any } = {}

  // First, check for providers based on type__field query
  // (Note: such a provider must return a value which is an object)
  const { providerFound, value } = getProviderValue(
    `${nodeName}__${fieldName}`,
    config,
    providedValues
  )
  if (providerFound && typeof value === 'object') {
    Object.entries(value).forEach(([argName, value]) => {
      const varName = `${nodeName}__${fieldName}__${argName}`
      // Only consider required arguments (provider can provide more than necessary)
      if (Object.keys(variableDefinitionsMap).includes(varName)) {
        variableValues[varName] = value
      }
    })
  }

  // Second, check for providers based on type__field__argument query
  // (Note: they overwrite possibly already provided values)
  requiredArguments.forEach((arg) => {
    const varName = `${nodeName}__${fieldName}__${arg.name.value}`
    const argType = schema.getType(getTypeName(arg.type))
    const { providerFound, value } = getProviderValue(
      varName,
      config,
      { ...variableValues, ...providedValues }, // pass already used variable values
      argType
    )
    if (providerFound) {
      variableValues[varName] = value
    }
  })

  // Third, populate all so-far neglected require variables with defaults or null
  requiredArguments.forEach((arg) => {
    const varName = `${nodeName}__${fieldName}__${arg.name.value}`
    const argType = schema.getType(getTypeName(arg.type))
    if (typeof variableValues[varName] === 'undefined') {
      if (isEnumType(argType)) {
        // Enum values can be randomly selected
        variableValues[varName] = getRandomEnum(argType)
      } else if (config.providePlaceholders) {
        variableValues[varName] = getDefaultArgValue(schema, config, arg.type)

        // Add default values for unfulfilled listSize directive if applicable
        const listSizeDirective = getListSizeDirective(field)
        if (listSizeDirective) {
          const value = getListSizeDirectiveDefaultValue(
            listSizeDirective,
            arg.type,
            config,
            schema
          )

          if (value !== undefined) {
            if (typeof value !== 'object') {
              variableValues[varName] = value
            } else {
              variableValues[varName] = merge.recursive(
                value,
                variableValues[varName]
              )
            }
          }
        }
      } else if (arg.type.kind === 'NonNullType') {
        throw new Error(
          `Missing provider for non-null variable "${varName}" of type "${print(
            arg.type
          )}". ` +
            `Either add a provider (e.g., using a wildcard "*__*" or "*__*__*"), ` +
            `or set providePlaceholders configuration option to true.`
        )
      } else {
        variableValues[varName] = null
      }
    }
  })

  return {
    args,
    variableDefinitionsMap,
    variableValues
  }
}