|
| 1 | +import type { GraphQLFieldResolver } from 'graphql/type/definition'; |
| 2 | + |
| 3 | +export type ElasticAggsT = { |
| 4 | + [outputFieldName: string]: ElasticAggsRulesT, |
| 5 | +}; |
| 6 | + |
| 7 | +export type ElasticAggsRulesT = { |
| 8 | + [aggOperationName: string]: mixed, |
| 9 | + aggs: ElasticAggsT, |
| 10 | +}; |
| 11 | + |
| 12 | +export type GqlAggBlock = { |
| 13 | + key: string, |
| 14 | + value: GqlAggRules, |
| 15 | +}; |
| 16 | + |
| 17 | +export type GqlAggRules = { |
| 18 | + [aggOperationName: string]: mixed, |
| 19 | + aggs: GqlAggBlock, |
| 20 | +}; |
| 21 | + |
| 22 | +export default function argsBlockConverter( |
| 23 | + resolve: GraphQLFieldResolver<*, *> |
| 24 | +): GraphQLFieldResolver<*, *> { |
| 25 | + return (source, args, context, info) => { |
| 26 | + if (args.body && Array.isArray(args.body.aggs)) { |
| 27 | + const aggs: GqlAggBlock[] = args.body.aggs; |
| 28 | + args.body.aggs = convertAggsBlocks(aggs); // eslint-disable-line |
| 29 | + } |
| 30 | + |
| 31 | + return resolve(source, args, context, info); |
| 32 | + }; |
| 33 | +} |
| 34 | + |
| 35 | +export function convertAggsBlocks(blockList: GqlAggBlock[]): ElasticAggsT { |
| 36 | + const result = {}; |
| 37 | + blockList.forEach(block => { |
| 38 | + if (block.key && block.value) { |
| 39 | + result[block.key] = convertAggsRules(block.value); |
| 40 | + } |
| 41 | + }); |
| 42 | + return result; |
| 43 | +} |
| 44 | + |
| 45 | +export function convertAggsRules(rules: GqlAggRules): ElasticAggsRulesT { |
| 46 | + const result = {}; |
| 47 | + Object.keys(rules).forEach(key => { |
| 48 | + if (key === 'aggs' && rules.aggs) { |
| 49 | + result.aggs = convertAggsBlocks(rules.aggs); |
| 50 | + } else { |
| 51 | + result[key] = rules[key]; |
| 52 | + } |
| 53 | + }); |
| 54 | + return result; |
| 55 | +} |
0 commit comments