-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathindex.ts
83 lines (73 loc) · 2.04 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import {
ComplexityEstimator,
ComplexityEstimatorArgs,
} from '../../QueryComplexity.js';
import {
getDirectiveValues,
GraphQLInt,
GraphQLList,
GraphQLNonNull,
GraphQLString,
GraphQLDirective,
DirectiveLocation,
} from 'graphql';
import get from 'lodash.get';
export type ComplexityDirectiveOptions = {
name?: string;
};
export function createComplexityDirective(
options?: ComplexityDirectiveOptions
): GraphQLDirective {
const mergedOptions = {
name: 'complexity',
...(options || {}),
};
return new GraphQLDirective({
name: mergedOptions.name,
description: 'Define a relation between the field and other nodes',
locations: [DirectiveLocation.FIELD_DEFINITION],
args: {
value: {
type: new GraphQLNonNull(GraphQLInt),
description: 'The complexity value for the field',
},
multipliers: {
type: new GraphQLList(new GraphQLNonNull(GraphQLString)),
},
},
});
}
export default function (
options: ComplexityDirectiveOptions = {}
): ComplexityEstimator {
const directive = createComplexityDirective(options);
return (args: ComplexityEstimatorArgs): number | void => {
// Ignore if astNode is undefined
if (!args.field.astNode) {
return;
}
const values = getDirectiveValues(directive, args.field.astNode);
// Ignore if no directive set
if (!values) {
return;
}
// Get multipliers
let totalMultiplier = 1;
if (values.multipliers && Array.isArray(values.multipliers)) {
totalMultiplier = values.multipliers.reduce(
(aggregated: number, multiplier: string) => {
const multiplierValue = get(args.args, multiplier);
if (typeof multiplierValue === 'number') {
return aggregated * multiplierValue;
}
if (Array.isArray(multiplierValue)) {
return aggregated * multiplierValue.length;
}
return aggregated;
},
totalMultiplier
);
}
return (Number(values.value) + args.childComplexity) * totalMultiplier;
};
}