Skip to content

Commit

Permalink
fix(graphql,aggregations): Exclude __typename in aggregations
Browse files Browse the repository at this point in the history
  • Loading branch information
doug-martin committed Jul 24, 2020
1 parent 99e06f4 commit 3897673
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 24 deletions.
4 changes: 3 additions & 1 deletion packages/query-graphql/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@
"lodash.omit": "^4.5.0",
"lower-case-first": "^2.0.1",
"pluralize": "^8.0.0",
"upper-case-first": "^2.0.1"
"upper-case-first": "^2.0.1",
"graphql-fields": "^2.0.3"
},
"peerDependencies": {
"@nestjs/common": "^7.0.0",
Expand All @@ -63,6 +64,7 @@
"@types/lodash.omit": "4.5.6",
"@types/node-fetch": "2.5.7",
"@types/pluralize": "0.0.29",
"@types/graphql-fields": "1.3.3",
"class-transformer": "0.2.3",
"class-validator": "0.12.2",
"dataloader": "2.0.0",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,30 +1,22 @@
import { AggregateQuery } from '@nestjs-query/core';
import { GraphQLResolveInfo, SelectionNode, FieldNode, Kind } from 'graphql';
import { GraphQLResolveInfo } from 'graphql';
import { GqlExecutionContext } from '@nestjs/graphql';
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import graphqlFields from 'graphql-fields';

const isFieldNode = (node: SelectionNode): node is FieldNode => {
return node.kind === Kind.FIELD;
};

const EXCLUDED_FIELDS = ['__typename'];
const QUERY_OPERATORS: (keyof AggregateQuery<unknown>)[] = ['count', 'avg', 'sum', 'min', 'max'];
export const AggregateQueryParam = createParamDecorator(<DTO>(data: unknown, ctx: ExecutionContext) => {
const info = GqlExecutionContext.create(ctx).getInfo<GraphQLResolveInfo>();
const query = info.fieldNodes.map(({ selectionSet }) => {
return selectionSet?.selections.reduce((aggQuery, selection) => {
if (isFieldNode(selection)) {
const aggType = selection.name.value;
const fields = selection.selectionSet?.selections
.map((s) => {
if (isFieldNode(s)) {
return s.name.value;
}
return undefined;
})
.filter((f) => !!f);
return { ...aggQuery, [aggType]: fields };
}
return aggQuery;
}, {} as AggregateQuery<DTO>);
})[0];
return query || {};
const fields = graphqlFields(info, {}, { excludedFields: EXCLUDED_FIELDS }) as Record<
keyof AggregateQuery<DTO>,
Record<keyof DTO, unknown>
>;
return QUERY_OPERATORS.filter((operator) => !!fields[operator]).reduce((query, operator) => {
const queryFields = Object.keys(fields[operator]) as (keyof DTO)[];
if (queryFields && queryFields.length) {
return { ...query, [operator]: queryFields };
}
return query;
}, {} as AggregateQuery<DTO>);
});

0 comments on commit 3897673

Please sign in to comment.