graphql#DirectiveNode TypeScript Examples

The following examples show how to use graphql#DirectiveNode. 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
/**
 * 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 #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 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 #3
Source File: appsync-visitor.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
private getDirectives(directives: readonly DirectiveNode[] | undefined): CodeGenDirectives {
    if (directives) {
      return directives.map(d => ({
        name: d.name.value,
        arguments: this.getDirectiveArguments(d),
      }));
    }
    return [];
  }
Example #4
Source File: appsync-visitor.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
private getDirectiveArguments(directive: DirectiveNode): CodeGenArgumentsMap {
    const directiveArguments: CodeGenArgumentsMap = {};
    if (directive.arguments) {
      directive.arguments.reduce((acc, arg) => {
        directiveArguments[arg.name.value] = valueFromASTUntyped(arg.value);
        return directiveArguments;
      }, directiveArguments);
    }
    return directiveArguments;
  }
Example #5
Source File: graphql.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
export function removeConnectionDirectives(ast: ASTNode) {
  return visit(ast, {
    Directive(node: DirectiveNode): DirectiveNode | null {
      switch(node.name.value) {
        // TODO: remove reference to 'connection' on transformer vNext release
        case 'connection':
          return null;
        case 'hasOne':
          return null;
        case 'belongsTo':
          return null;
        case 'hasMany':
          return null;
        case 'manyToMany':
          return null;
        default:
          return node;
      }
    },
  });
}
Example #6
Source File: ttl-transformer.ts    From graphql-ttl-transformer with MIT License 6 votes vote down vote up
public field = (
    parent: ObjectTypeDefinitionNode | InterfaceTypeDefinitionNode,
    definition: FieldDefinitionNode,
    directive: DirectiveNode,
    acc: TransformerContext
  ) => {
    if (!["AWSTimestamp", "Int"].includes(getBaseType(definition.type))) {
      throw new InvalidDirectiveError(
        'Directive "ttl" must be used only on AWSTimestamp or Int type fields.'
      );
    }

    let numberOfTtlDirectivesInsideParentType = 0;
    if (parent.fields) {
      parent.fields.forEach((field) => {
        if (field.directives) {
          numberOfTtlDirectivesInsideParentType += field.directives.filter(
            (directive) => directive.name.value === "ttl"
          ).length;
        }
      });
    }
    if (numberOfTtlDirectivesInsideParentType > 1) {
      throw new InvalidDirectiveError(
        'Directive "ttl" must be used only once in the same type.'
      );
    }

    const tableName = ModelResourceIDs.ModelTableResourceID(parent.name.value);
    const table = acc.getResource(tableName);
    const fieldName = definition.name.value;
    table.Properties = {
      ...table.Properties,
      TimeToLiveSpecification: {
        AttributeName: fieldName,
        Enabled: true,
      },
    };
  };
Example #7
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 #8
Source File: generate-query.ts    From graphql-query-generator with MIT License 5 votes vote down vote up
/**
 * Given a field node, return the listSize directive, if it exists
 */
function getListSizeDirective(field: FieldDefinitionNode): DirectiveNode {
  return field?.directives.find((dir) => dir.name.value === 'listSize')
}
Example #9
Source File: generate-query.ts    From graphql-query-generator with MIT License 5 votes vote down vote up
/**
 * For a given listSize directive, return a default value for it
 */
function getListSizeDirectiveDefaultValue(
  listSizeDirective: DirectiveNode,
  typeNode: TypeNode,
  config: InternalConfiguration,
  schema: GraphQLSchema
) {
  // if requiredOneSlicingArg is false then we do not add anything because none of the slicingArguments are required
  const requireOneSlicingArg = getRequireOneSlicingArgument(listSizeDirective)
  if (
    requireOneSlicingArg &&
    (requireOneSlicingArg.value as BooleanValueNode).value === false
  ) {
    return undefined
  }

  const slicingArgumentsArg = getSlicingArguments(listSizeDirective)
  if (!slicingArgumentsArg) return undefined

  /**
   * Already checked slicingArgumentsArguments is a list
   *
   * Extract paths from slicingArgumentsArguments
   */
  const slicingArgumentsPaths = (slicingArgumentsArg.value as ListValueNode).values.map(
    (value) => {
      if (value.kind === 'StringValue') return value.value
    }
  )

  if (slicingArgumentsPaths.length > 0) {
    const slicingArgumentsTokenizedPath = slicingArgumentsPaths[0].split('.')
    return getListSizeDirectiveDefaultValueHelper(
      slicingArgumentsTokenizedPath,
      typeNode,
      config,
      schema
    )
  }
}
Example #10
Source File: alphabetize.ts    From graphql-eslint with MIT License 4 votes vote down vote up
rule: GraphQLESLintRule<[AlphabetizeConfig]> = {
  meta: {
    type: 'suggestion',
    fixable: 'code',
    docs: {
      category: ['Schema', 'Operations'],
      description:
        'Enforce arrange in alphabetical order for type fields, enum values, input object fields, operation selections and more.',
      url: `https://github.com/B2o5T/graphql-eslint/blob/master/docs/rules/${RULE_ID}.md`,
      examples: [
        {
          title: 'Incorrect',
          usage: [{ fields: [Kind.OBJECT_TYPE_DEFINITION] }],
          code: /* GraphQL */ `
            type User {
              password: String
              firstName: String! # should be before "password"
              age: Int # should be before "firstName"
              lastName: String!
            }
          `,
        },
        {
          title: 'Correct',
          usage: [{ fields: [Kind.OBJECT_TYPE_DEFINITION] }],
          code: /* GraphQL */ `
            type User {
              age: Int
              firstName: String!
              lastName: String!
              password: String
            }
          `,
        },
        {
          title: 'Incorrect',
          usage: [{ values: [Kind.ENUM_TYPE_DEFINITION] }],
          code: /* GraphQL */ `
            enum Role {
              SUPER_ADMIN
              ADMIN # should be before "SUPER_ADMIN"
              USER
              GOD # should be before "USER"
            }
          `,
        },
        {
          title: 'Correct',
          usage: [{ values: [Kind.ENUM_TYPE_DEFINITION] }],
          code: /* GraphQL */ `
            enum Role {
              ADMIN
              GOD
              SUPER_ADMIN
              USER
            }
          `,
        },
        {
          title: 'Incorrect',
          usage: [{ selections: [Kind.OPERATION_DEFINITION] }],
          code: /* GraphQL */ `
            query {
              me {
                firstName
                lastName
                email # should be before "lastName"
              }
            }
          `,
        },
        {
          title: 'Correct',
          usage: [{ selections: [Kind.OPERATION_DEFINITION] }],
          code: /* GraphQL */ `
            query {
              me {
                email
                firstName
                lastName
              }
            }
          `,
        },
      ],
      configOptions: {
        schema: [
          {
            fields: fieldsEnum,
            values: valuesEnum,
            arguments: argumentsEnum,
            // TODO: add in graphql-eslint v4
            // definitions: true,
          },
        ],
        operations: [
          {
            selections: selectionsEnum,
            variables: variablesEnum,
            arguments: [Kind.FIELD, Kind.DIRECTIVE],
          },
        ],
      },
    },
    messages: {
      [RULE_ID]: '`{{ currName }}` should be before {{ prevName }}.',
    },
    schema: {
      type: 'array',
      minItems: 1,
      maxItems: 1,
      items: {
        type: 'object',
        additionalProperties: false,
        minProperties: 1,
        properties: {
          fields: {
            ...ARRAY_DEFAULT_OPTIONS,
            items: {
              enum: fieldsEnum,
            },
            description: 'Fields of `type`, `interface`, and `input`.',
          },
          values: {
            ...ARRAY_DEFAULT_OPTIONS,
            items: {
              enum: valuesEnum,
            },
            description: 'Values of `enum`.',
          },
          selections: {
            ...ARRAY_DEFAULT_OPTIONS,
            items: {
              enum: selectionsEnum,
            },
            description: 'Selections of `fragment` and operations `query`, `mutation` and `subscription`.',
          },
          variables: {
            ...ARRAY_DEFAULT_OPTIONS,
            items: {
              enum: variablesEnum,
            },
            description: 'Variables of operations `query`, `mutation` and `subscription`.',
          },
          arguments: {
            ...ARRAY_DEFAULT_OPTIONS,
            items: {
              enum: argumentsEnum,
            },
            description: 'Arguments of fields and directives.',
          },
          definitions: {
            type: 'boolean',
            description: 'Definitions – `type`, `interface`, `enum`, `scalar`, `input`, `union` and `directive`.',
            default: false,
          },
        },
      },
    },
  },
  create(context) {
    const sourceCode = context.getSourceCode();

    function isNodeAndCommentOnSameLine(node: { loc: SourceLocation }, comment: Comment): boolean {
      return node.loc.end.line === comment.loc.start.line;
    }

    function getBeforeComments(node): Comment[] {
      const commentsBefore = sourceCode.getCommentsBefore(node);
      if (commentsBefore.length === 0) {
        return [];
      }
      const tokenBefore = sourceCode.getTokenBefore(node);
      if (tokenBefore) {
        return commentsBefore.filter(comment => !isNodeAndCommentOnSameLine(tokenBefore, comment));
      }
      const filteredComments = [];
      const nodeLine = node.loc.start.line;
      // Break on comment that not attached to node
      for (let i = commentsBefore.length - 1; i >= 0; i -= 1) {
        const comment = commentsBefore[i];
        if (nodeLine - comment.loc.start.line - filteredComments.length > 1) {
          break;
        }
        filteredComments.unshift(comment);
      }
      return filteredComments;
    }

    function getRangeWithComments(node): AST.Range {
      if (node.kind === Kind.VARIABLE) {
        node = node.parent;
      }
      const [firstBeforeComment] = getBeforeComments(node);
      const [firstAfterComment] = sourceCode.getCommentsAfter(node);
      const from = firstBeforeComment || node;
      const to = firstAfterComment && isNodeAndCommentOnSameLine(node, firstAfterComment) ? firstAfterComment : node;
      return [from.range[0], to.range[1]];
    }

    function checkNodes(nodes: GraphQLESTreeNode<ASTNode>[]) {
      // Starts from 1, ignore nodes.length <= 1
      for (let i = 1; i < nodes.length; i += 1) {
        const currNode = nodes[i];
        const currName = 'name' in currNode && currNode.name?.value;
        if (!currName) {
          // we don't move unnamed current nodes
          continue;
        }

        const prevNode = nodes[i - 1];
        const prevName = 'name' in prevNode && prevNode.name?.value;
        if (prevName) {
          // Compare with lexicographic order
          const compareResult = prevName.localeCompare(currName);
          const shouldSort = compareResult === 1;
          if (!shouldSort) {
            const isSameName = compareResult === 0;
            if (!isSameName || !prevNode.kind.endsWith('Extension') || currNode.kind.endsWith('Extension')) {
              continue;
            }
          }
        }

        context.report({
          node: currNode.name,
          messageId: RULE_ID,
          data: {
            currName,
            prevName: prevName ? `\`${prevName}\`` : lowerCase(prevNode.kind),
          },
          *fix(fixer) {
            const prevRange = getRangeWithComments(prevNode);
            const currRange = getRangeWithComments(currNode);
            yield fixer.replaceTextRange(prevRange, sourceCode.getText({ range: currRange } as any));
            yield fixer.replaceTextRange(currRange, sourceCode.getText({ range: prevRange } as any));
          },
        });
      }
    }

    const opts = context.options[0];
    const fields = new Set(opts.fields ?? []);
    const listeners: GraphQLESLintRuleListener = {};

    const kinds = [
      fields.has(Kind.OBJECT_TYPE_DEFINITION) && [Kind.OBJECT_TYPE_DEFINITION, Kind.OBJECT_TYPE_EXTENSION],
      fields.has(Kind.INTERFACE_TYPE_DEFINITION) && [Kind.INTERFACE_TYPE_DEFINITION, Kind.INTERFACE_TYPE_EXTENSION],
      fields.has(Kind.INPUT_OBJECT_TYPE_DEFINITION) && [
        Kind.INPUT_OBJECT_TYPE_DEFINITION,
        Kind.INPUT_OBJECT_TYPE_EXTENSION,
      ],
    ]
      .filter(Boolean)
      .flat();

    const fieldsSelector = kinds.join(',');

    const hasEnumValues = opts.values?.[0] === Kind.ENUM_TYPE_DEFINITION;
    const selectionsSelector = opts.selections?.join(',');
    const hasVariables = opts.variables?.[0] === Kind.OPERATION_DEFINITION;
    const argumentsSelector = opts.arguments?.join(',');

    if (fieldsSelector) {
      listeners[fieldsSelector] = (
        node: GraphQLESTreeNode<
          | ObjectTypeDefinitionNode
          | ObjectTypeExtensionNode
          | InterfaceTypeDefinitionNode
          | InterfaceTypeExtensionNode
          | InputObjectTypeDefinitionNode
          | InputObjectTypeExtensionNode
        >
      ) => {
        checkNodes(node.fields);
      };
    }

    if (hasEnumValues) {
      const enumValuesSelector = [Kind.ENUM_TYPE_DEFINITION, Kind.ENUM_TYPE_EXTENSION].join(',');
      listeners[enumValuesSelector] = (node: GraphQLESTreeNode<EnumTypeDefinitionNode | EnumTypeExtensionNode>) => {
        checkNodes(node.values);
      };
    }

    if (selectionsSelector) {
      listeners[`:matches(${selectionsSelector}) SelectionSet`] = (node: GraphQLESTreeNode<SelectionSetNode>) => {
        checkNodes(
          node.selections.map(selection =>
            // sort by alias is field is renamed
            'alias' in selection && selection.alias ? ({ name: selection.alias } as any) : selection
          )
        );
      };
    }

    if (hasVariables) {
      listeners.OperationDefinition = (node: GraphQLESTreeNode<OperationDefinitionNode>) => {
        checkNodes(node.variableDefinitions.map(varDef => varDef.variable));
      };
    }

    if (argumentsSelector) {
      listeners[argumentsSelector] = (
        node: GraphQLESTreeNode<FieldDefinitionNode | FieldNode | DirectiveDefinitionNode | DirectiveNode>
      ) => {
        checkNodes(node.arguments);
      };
    }

    if (opts.definitions) {
      listeners.Document = node => {
        checkNodes(node.definitions);
      };
    }

    return listeners;
  },
}
Example #11
Source File: graphql-js-validation.ts    From graphql-eslint with MIT License 4 votes vote down vote up
GRAPHQL_JS_VALIDATIONS: Record<string, GraphQLESLintRule> = Object.assign(
  {},
  validationToRule('executable-definitions', 'ExecutableDefinitions', {
    category: 'Operations',
    description:
      'A GraphQL document is only valid for execution if all definitions are either operation or fragment definitions.',
    requiresSchema: true,
  }),
  validationToRule('fields-on-correct-type', 'FieldsOnCorrectType', {
    category: 'Operations',
    description:
      'A GraphQL document is only valid if all fields selected are defined by the parent type, or are an allowed meta field such as `__typename`.',
    requiresSchema: true,
  }),
  validationToRule('fragments-on-composite-type', 'FragmentsOnCompositeTypes', {
    category: 'Operations',
    description:
      'Fragments use a type condition to determine if they apply, since fragments can only be spread into a composite type (object, interface, or union), the type condition must also be a composite type.',
    requiresSchema: true,
  }),
  validationToRule('known-argument-names', 'KnownArgumentNames', {
    category: ['Schema', 'Operations'],
    description: 'A GraphQL field is only valid if all supplied arguments are defined by that field.',
    requiresSchema: true,
  }),
  validationToRule(
    'known-directives',
    'KnownDirectives',
    {
      category: ['Schema', 'Operations'],
      description:
        'A GraphQL document is only valid if all `@directive`s are known by the schema and legally positioned.',
      requiresSchema: true,
      examples: [
        {
          title: 'Valid',
          usage: [{ ignoreClientDirectives: ['client'] }],
          code: /* GraphQL */ `
            {
              product {
                someClientField @client
              }
            }
          `,
        },
      ],
    },
    ({ context, node: documentNode }) => {
      const { ignoreClientDirectives = [] } = context.options[0] || {};
      if (ignoreClientDirectives.length === 0) {
        return documentNode;
      }

      const filterDirectives = (node: { directives?: ReadonlyArray<DirectiveNode> }) => ({
        ...node,
        directives: node.directives.filter(directive => !ignoreClientDirectives.includes(directive.name.value)),
      });

      return visit(documentNode, {
        Field: filterDirectives,
        OperationDefinition: filterDirectives,
      });
    },
    {
      type: 'array',
      maxItems: 1,
      items: {
        type: 'object',
        additionalProperties: false,
        required: ['ignoreClientDirectives'],
        properties: {
          ignoreClientDirectives: ARRAY_DEFAULT_OPTIONS,
        },
      },
    }
  ),
  validationToRule(
    'known-fragment-names',
    'KnownFragmentNames',
    {
      category: 'Operations',
      description:
        'A GraphQL document is only valid if all `...Fragment` fragment spreads refer to fragments defined in the same document.',
      requiresSchema: true,
      requiresSiblings: true,
      examples: [
        {
          title: 'Incorrect',
          code: /* GraphQL */ `
            query {
              user {
                id
                ...UserFields # fragment not defined in the document
              }
            }
          `,
        },
        {
          title: 'Correct',
          code: /* GraphQL */ `
            fragment UserFields on User {
              firstName
              lastName
            }

            query {
              user {
                id
                ...UserFields
              }
            }
          `,
        },
        {
          title: 'Correct (`UserFields` fragment located in a separate file)',
          code: /* GraphQL */ `
            # user.gql
            query {
              user {
                id
                ...UserFields
              }
            }

            # user-fields.gql
            fragment UserFields on User {
              id
            }
          `,
        },
      ],
    },
    handleMissingFragments
  ),
  validationToRule('known-type-names', 'KnownTypeNames', {
    category: ['Schema', 'Operations'],
    description:
      'A GraphQL document is only valid if referenced types (specifically variable definitions and fragment conditions) are defined by the type schema.',
    requiresSchema: true,
  }),
  validationToRule('lone-anonymous-operation', 'LoneAnonymousOperation', {
    category: 'Operations',
    description:
      'A GraphQL document is only valid if when it contains an anonymous operation (the query short-hand) that it contains only that one operation definition.',
    requiresSchema: true,
  }),
  validationToRule('lone-schema-definition', 'LoneSchemaDefinition', {
    category: 'Schema',
    description: 'A GraphQL document is only valid if it contains only one schema definition.',
  }),
  validationToRule('no-fragment-cycles', 'NoFragmentCycles', {
    category: 'Operations',
    description: 'A GraphQL fragment is only valid when it does not have cycles in fragments usage.',
    requiresSchema: true,
  }),
  validationToRule(
    'no-undefined-variables',
    'NoUndefinedVariables',
    {
      category: 'Operations',
      description:
        'A GraphQL operation is only valid if all variables encountered, both directly and via fragment spreads, are defined by that operation.',
      requiresSchema: true,
      requiresSiblings: true,
    },
    handleMissingFragments
  ),
  validationToRule(
    'no-unused-fragments',
    'NoUnusedFragments',
    {
      category: 'Operations',
      description:
        'A GraphQL document is only valid if all fragment definitions are spread within operations, or spread within other fragments spread within operations.',
      requiresSchema: true,
      requiresSiblings: true,
    },
    ({ ruleId, context, node }) => {
      const siblings = requireSiblingsOperations(ruleId, context);
      const FilePathToDocumentsMap = [...siblings.getOperations(), ...siblings.getFragments()].reduce<
        Record<string, ExecutableDefinitionNode[]>
      >((map, { filePath, document }) => {
        map[filePath] ??= [];
        map[filePath].push(document);
        return map;
      }, Object.create(null));

      const getParentNode = (currentFilePath: string, node: DocumentNode): DocumentNode => {
        const { fragmentDefs } = getFragmentDefsAndFragmentSpreads(node);
        if (fragmentDefs.size === 0) {
          return node;
        }
        // skip iteration over documents for current filepath
        delete FilePathToDocumentsMap[currentFilePath];

        for (const [filePath, documents] of Object.entries(FilePathToDocumentsMap)) {
          const missingFragments = getMissingFragments({
            kind: Kind.DOCUMENT,
            definitions: documents,
          });
          const isCurrentFileImportFragment = missingFragments.some(fragment => fragmentDefs.has(fragment));

          if (isCurrentFileImportFragment) {
            return getParentNode(filePath, {
              kind: Kind.DOCUMENT,
              definitions: [...node.definitions, ...documents],
            });
          }
        }
        return node;
      };

      return getParentNode(context.getFilename(), node);
    }
  ),
  validationToRule(
    'no-unused-variables',
    'NoUnusedVariables',
    {
      category: 'Operations',
      description:
        'A GraphQL operation is only valid if all variables defined by an operation are used, either directly or within a spread fragment.',
      requiresSchema: true,
      requiresSiblings: true,
    },
    handleMissingFragments
  ),
  validationToRule('overlapping-fields-can-be-merged', 'OverlappingFieldsCanBeMerged', {
    category: 'Operations',
    description:
      'A selection set is only valid if all fields (including spreading any fragments) either correspond to distinct response names or can be merged without ambiguity.',
    requiresSchema: true,
  }),
  validationToRule('possible-fragment-spread', 'PossibleFragmentSpreads', {
    category: 'Operations',
    description:
      'A fragment spread is only valid if the type condition could ever possibly be true: if there is a non-empty intersection of the possible parent types, and possible types which pass the type condition.',
    requiresSchema: true,
  }),
  validationToRule('possible-type-extension', 'PossibleTypeExtensions', {
    category: 'Schema',
    description: 'A type extension is only valid if the type is defined and has the same kind.',
    // TODO: add in graphql-eslint v4
    recommended: false,
    requiresSchema: true,
    isDisabledForAllConfig: true,
  }),
  validationToRule('provided-required-arguments', 'ProvidedRequiredArguments', {
    category: ['Schema', 'Operations'],
    description:
      'A field or directive is only valid if all required (non-null without a default value) field arguments have been provided.',
    requiresSchema: true,
  }),
  validationToRule('scalar-leafs', 'ScalarLeafs', {
    category: 'Operations',
    description:
      'A GraphQL document is valid only if all leaf fields (fields without sub selections) are of scalar or enum types.',
    requiresSchema: true,
  }),
  validationToRule('one-field-subscriptions', 'SingleFieldSubscriptions', {
    category: 'Operations',
    description: 'A GraphQL subscription is valid only if it contains a single root field.',
    requiresSchema: true,
  }),
  validationToRule('unique-argument-names', 'UniqueArgumentNames', {
    category: 'Operations',
    description: 'A GraphQL field or directive is only valid if all supplied arguments are uniquely named.',
    requiresSchema: true,
  }),
  validationToRule('unique-directive-names', 'UniqueDirectiveNames', {
    category: 'Schema',
    description: 'A GraphQL document is only valid if all defined directives have unique names.',
  }),
  validationToRule('unique-directive-names-per-location', 'UniqueDirectivesPerLocation', {
    category: ['Schema', 'Operations'],
    description:
      'A GraphQL document is only valid if all non-repeatable directives at a given location are uniquely named.',
    requiresSchema: true,
  }),
  validationToRule('unique-enum-value-names', 'UniqueEnumValueNames', {
    category: 'Schema',
    description: 'A GraphQL enum type is only valid if all its values are uniquely named.',
    recommended: false,
    isDisabledForAllConfig: true,
  }),
  validationToRule('unique-field-definition-names', 'UniqueFieldDefinitionNames', {
    category: 'Schema',
    description: 'A GraphQL complex type is only valid if all its fields are uniquely named.',
  }),
  validationToRule('unique-input-field-names', 'UniqueInputFieldNames', {
    category: 'Operations',
    description: 'A GraphQL input object value is only valid if all supplied fields are uniquely named.',
  }),
  validationToRule('unique-operation-types', 'UniqueOperationTypes', {
    category: 'Schema',
    description: 'A GraphQL document is only valid if it has only one type per operation.',
  }),
  validationToRule('unique-type-names', 'UniqueTypeNames', {
    category: 'Schema',
    description: 'A GraphQL document is only valid if all defined types have unique names.',
  }),
  validationToRule('unique-variable-names', 'UniqueVariableNames', {
    category: 'Operations',
    description: 'A GraphQL operation is only valid if all its variables are uniquely named.',
    requiresSchema: true,
  }),
  validationToRule('value-literals-of-correct-type', 'ValuesOfCorrectType', {
    category: 'Operations',
    description: 'A GraphQL document is only valid if all value literals are of the type expected at their position.',
    requiresSchema: true,
  }),
  validationToRule('variables-are-input-types', 'VariablesAreInputTypes', {
    category: 'Operations',
    description:
      'A GraphQL operation is only valid if all the variables it defines are of input types (scalar, enum, or input object).',
    requiresSchema: true,
  }),
  validationToRule('variables-in-allowed-position', 'VariablesInAllowedPosition', {
    category: 'Operations',
    description: 'Variables passed to field arguments conform to type.',
    requiresSchema: true,
  })
)
Example #12
Source File: require-deprecation-date.ts    From graphql-eslint with MIT License 4 votes vote down vote up
rule: GraphQLESLintRule<[{ argumentName?: string }]> = {
  meta: {
    type: 'suggestion',
    hasSuggestions: true,
    docs: {
      category: 'Schema',
      description:
        'Require deletion date on `@deprecated` directive. Suggest removing deprecated things after deprecated date.',
      url: 'https://github.com/B2o5T/graphql-eslint/blob/master/docs/rules/require-deprecation-date.md',
      examples: [
        {
          title: 'Incorrect',
          code: /* GraphQL */ `
            type User {
              firstname: String @deprecated
              firstName: String
            }
          `,
        },
        {
          title: 'Incorrect',
          code: /* GraphQL */ `
            type User {
              firstname: String @deprecated(reason: "Use 'firstName' instead")
              firstName: String
            }
          `,
        },
        {
          title: 'Correct',
          code: /* GraphQL */ `
            type User {
              firstname: String @deprecated(reason: "Use 'firstName' instead", deletionDate: "25/12/2022")
              firstName: String
            }
          `,
        },
      ],
    },
    messages: {
      [MESSAGE_REQUIRE_DATE]: 'Directive "@deprecated" must have a deletion date',
      [MESSAGE_INVALID_FORMAT]: 'Deletion date must be in format "DD/MM/YYYY"',
      [MESSAGE_INVALID_DATE]: 'Invalid "{{ deletionDate }}" deletion date',
      [MESSAGE_CAN_BE_REMOVED]: '"{{ nodeName }}" сan be removed',
    },
    schema: [
      {
        type: 'object',
        additionalProperties: false,
        properties: {
          argumentName: {
            type: 'string',
          },
        },
      },
    ],
  },
  create(context) {
    return {
      'Directive[name.value=deprecated]'(node: GraphQLESTreeNode<DirectiveNode>) {
        const argName = context.options[0]?.argumentName || 'deletionDate';
        const deletionDateNode = node.arguments.find(arg => arg.name.value === argName);

        if (!deletionDateNode) {
          context.report({
            node: node.name,
            messageId: MESSAGE_REQUIRE_DATE,
          });
          return;
        }
        const deletionDate = valueFromNode(deletionDateNode.value as any);
        const isValidDate = DATE_REGEX.test(deletionDate);

        if (!isValidDate) {
          context.report({ node: deletionDateNode.value, messageId: MESSAGE_INVALID_FORMAT });
          return;
        }
        let [day, month, year] = deletionDate.split('/');
        day = day.padStart(2, '0');
        month = month.padStart(2, '0');
        const deletionDateInMS = Date.parse(`${year}-${month}-${day}`);

        if (Number.isNaN(deletionDateInMS)) {
          context.report({
            node: deletionDateNode.value,
            messageId: MESSAGE_INVALID_DATE,
            data: {
              deletionDate,
            },
          });
          return;
        }

        const canRemove = Date.now() > deletionDateInMS;

        if (canRemove) {
          const { parent } = node as any;
          const nodeName = parent.name.value;
          context.report({
            node: parent.name,
            messageId: MESSAGE_CAN_BE_REMOVED,
            data: { nodeName },
            suggest: [
              {
                desc: `Remove \`${nodeName}\``,
                fix: fixer => fixer.remove(parent),
              },
            ],
          });
        }
      },
    };
  },
}