Skip to content

Commit

Permalink
fix(lsp): surface unused fragment definition leaves (#299)
Browse files Browse the repository at this point in the history
  • Loading branch information
JoviDeCroock committed Apr 20, 2024
1 parent 4ca851c commit 19551c5
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/wise-coins-look.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@0no-co/graphqlsp': patch
---

Correctly identify unused fields on a fragment-definition, these have no parent to group by so we display them as unused leaves
1 change: 1 addition & 0 deletions packages/example-tada/src/Pokemon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { FragmentOf, graphql, readFragment } from './graphql';
export const Fields = { Pokemon: graphql(`
fragment Pok on Pokemon {
resistant
types
}`)
}

Expand Down
26 changes: 21 additions & 5 deletions packages/graphqlsp/src/fieldUsage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -495,18 +495,22 @@ export const checkFieldUsageInFile = (
const unused = allPaths.filter(x => !allAccess.includes(x));
const aggregatedUnusedFields = new Set<string>();
const unusedChildren: { [key: string]: Set<string> } = {};
const unusedFragmentLeaf = new Set<string>();
unused.forEach(unusedField => {
const split = unusedField.split('.');
split.pop();
const parentField = split.join('.');
const loc = fieldToLoc.get(parentField);
if (!loc) return;

aggregatedUnusedFields.add(parentField);
if (unusedChildren[parentField]) {
unusedChildren[parentField].add(unusedField);
if (loc) {
aggregatedUnusedFields.add(parentField);
if (unusedChildren[parentField]) {
unusedChildren[parentField].add(unusedField);
} else {
unusedChildren[parentField] = new Set([unusedField]);
}
} else {
unusedChildren[parentField] = new Set([unusedField]);
unusedFragmentLeaf.add(unusedField);
}
});

Expand All @@ -524,6 +528,18 @@ export const checkFieldUsageInFile = (
.join(', ')} are not used.`,
});
});

unusedFragmentLeaf.forEach(field => {
const loc = fieldToLoc.get(field)!;
diagnostics.push({
file: source,
length: loc.length,
start: node.getStart() + loc.start + 1,
category: ts.DiagnosticCategory.Warning,
code: UNUSED_FIELD_CODE,
messageText: `Field ${field} is not used.`,
});
});
});
} catch (e: any) {
console.error('[GraphQLSP]: ', e.message, e.stack);
Expand Down

0 comments on commit 19551c5

Please sign in to comment.