@@ -6,9 +6,9 @@ const Actions = require('../action-util');
66/**
77 * Populate an association
88 *
9- * get /model/:parentid/relation
10- * get /model/:parentid/relation/count
11- * get /model/:parentid/relation/:id
9+ * get /model/:parentid/: relation
10+ * get /model/:parentid/: relation/count
11+ * get /model/:parentid/: relation/:id
1212 *
1313 * @param {Object } where - the find criteria (passed directly to the ORM)
1414 * @param {Integer } limit - the maximum number of records to send back (useful for pagination)
@@ -21,7 +21,7 @@ module.exports = function expand(route, options) {
2121
2222 return async ( request , h ) => {
2323
24- const actionUtil = Actions ( request , options ) ;
24+ const actionUtil = Actions ( request , options , h ) ;
2525
2626 const Model = actionUtil . modelFromParam ( options . model ) ;
2727 const relation = options . associationAttr ;
@@ -37,6 +37,8 @@ module.exports = function expand(route, options) {
3737 const rangeStart = actionUtil . parseSkip ( ) ;
3838 const rangeEnd = rangeStart + limit ;
3939
40+ let total ;
41+
4042 const modelFullQuery = Model . query ( ) . findById ( keys . parent . value )
4143 . withGraphFetched ( relation )
4244 . modifyGraph ( relation , ( builder ) => {
@@ -45,6 +47,12 @@ module.exports = function expand(route, options) {
4547 builder . where ( Ref ( RelationModel . tableName + '.' + keys . child . key ) , '=' , keys . child . value ) ;
4648 }
4749
50+ if ( options . includeTotalCount ) {
51+ // we need to wrap this in an async iffe to trigger the query,
52+ // as otherwise the main query gets borked
53+ total = ( async ( ) => await builder . clone ( ) . count ( { total : Ref ( RelationModel . tableName + '.' + keys . child . key ) } ) . first ( ) ) ( ) ;
54+ }
55+
4856 builder . range ( rangeStart , rangeEnd ) . limit ( limit ) ;
4957
5058 if ( sort ) {
@@ -66,10 +74,14 @@ module.exports = function expand(route, options) {
6674 return Boom . notFound ( ) ;
6775 }
6876
77+ if ( total ) {
78+ return actionUtil . replyWithRange ( options . associationAttr , rangeStart , rangeEnd , await total , modelFull [ options . associationAttr ] ) ;
79+ }
80+
6981 if ( options . _private . count ) {
7082 return modelFull [ options . associationAttr ] . length ;
7183 }
7284
73- return modelFull ;
85+ return modelFull [ options . associationAttr ] ;
7486 } ;
7587} ;
0 commit comments