check-fetch-policy

Try in Playground
apollo-graphql-client-javascriptUnknownInformational

0

No tags

No CWE or CVE

Ast Rule: function call


check-fetch-policy

How to write a rule
function visit(node, filename, code) {


  const checkFetchPolicyValue = (element) => {
    const VALID_CACHE_POLICY = ['cache-first', 'cache-only', 'cache-and-network', 'network-only', 'no-cache', 'standby'];
    if (element.astType !== "string") {
      return;
    }

    if (!element.value || element.value.length === 0) {
      return;
    }

    const v = element.value.substring(1, element.value.length - 1);

    if (!VALID_CACHE_POLICY.includes(v)) {
      const error = buildError(element.start.line, element.start.col, element.end.line, element.end.col,
        "Invalid fetch policy", "WARNING", "BEST_PRACTICE");
      const edit = buildEditUpdate(element.start.line, element.start.col, element.end.line, element.end.col, '"cache-first"');
      const fix = buildFix('Use cache-first policy', [edit]);
      addError(error.addFix(fix));
    }

  }

  if (!node || !node.functionName || !node.functionName.value || node.functionName.value !== "useQuery" || !node.arguments) {
    return;
  }

  const arguments = node.arguments.values;


  if (arguments.length === 2) {
    const secondArgument = arguments[1].value;
    if (secondArgument.astType !== "object") {
      return;
    }

    ITEMS_TO_CHECK = ["fetchPolicy", "nextFetchPolicy"];

    ITEMS_TO_CHECK.forEach((fp) => {
      const fetchPolicy = secondArgument.elements.filter(e => e.name && e.name.value && e.name.value === fp);

      if (fetchPolicy.length > 0) {
        checkFetchPolicyValue(fetchPolicy[0].value);
      }
    });
  }

}

no-policy.js

Expected test result: no error

const { loading, error, data } = useQuery(GET_DOGS, {
});

correct.js

Expected test result: no error

const { loading, error, data } = useQuery(GET_DOGS, {
  fetchPolicy: 'network-only', // Used for first execution
  nextFetchPolicy: 'cache-first', // Used for subsequent executions
});

error.js

Expected test result: has error

const { loading, error, data } = useQuery(GET_DOGS, {
  fetchPolicy: 'wedwedwedwedwed', // Used for first execution
  nextFetchPolicy: 'fgethrthrth', // Used for subsequent executions
});
Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Playground
  • Snippets
  • Cookbooks
Legal
  • Security
  • Privacy Policy
  • Code Privacy
  • Terms of Service
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.