import type { Plugin } from "graphile-build" ; import type { QueryBuilder } from "graphile-build-pg" ; import type { GraphQLResolveInfo , GraphQLObjectType } from "graphql" ; const AddAggregatesPlugin = ( builder ) => { builder . hook ( "GraphQLObjectType:fields" , ( fields , build , context ) => { const { inflection , getSafeAliasFromResolveInfo , pgSql : sql , getSafeAliasFromAlias , pgQueryFromResolveData : queryFromResolveData , } = build ; const { fieldWithHooks , scope : { isPgRowConnectionType , pgIntrospection : table } , } = context ; if ( ! isPgRowConnectionType || ! table || table . kind !== "class" || ! table . namespace ) { return fields ; } const AggregateContainerType = build . getTypeByName ( inflection . aggregateContainerType ( table ) ) ; if ( ! AggregateContainerType || Object . keys ( AggregateContainerType . getFields ( ) ) . length === 0 ) { return fields ; } const fieldName = inflection . aggregatesContainerField ( table ) ; return { ... fields , [ fieldName ] : fieldWithHooks ( fieldName , ( { addDataGenerator , getDataFromParsedResolveInfoFragment } ) => { addDataGenerator ( ( parsedResolveInfoFragment ) => { const safeAlias = getSafeAliasFromAlias ( parsedResolveInfoFragment . alias ) ; const resolveData = getDataFromParsedResolveInfoFragment ( parsedResolveInfoFragment , AggregateContainerType ) ; return { pgNamedQuery : { name : "aggregates" , query : ( aggregateQueryBuilder ) => { aggregateQueryBuilder . select ( ( ) => { const query = queryFromResolveData ( sql . identifier ( Symbol ( ) ) , aggregateQueryBuilder . getTableAlias ( ) , resolveData , { onlyJsonField : true } , ( innerQueryBuilder ) => { innerQueryBuilder . parentQueryBuilder = aggregateQueryBuilder ; innerQueryBuilder . select ( sql . fragment `sum(1)` , "__force_aggregate__" ) ; } , aggregateQueryBuilder . context ) ; return sql . fragment `(${ query })` ; } , safeAlias ) ; } , } , } ; } ) ; return { description : `Aggregates across the matching connection (ignoring before/after/first/last/offset)` , type : AggregateContainerType , resolve ( parent , _args , _context , resolveInfo ) { const safeAlias = getSafeAliasFromResolveInfo ( resolveInfo ) ; return parent . aggregates [ safeAlias ] || 0 ; } , } ; } , { } ) , } ; } ) ; } ; export default AddAggregatesPlugin ;