@@ -6,27 +6,22 @@ const { Box, User } = require('@sensebox/opensensemap-api-models'),
66 handleError = require ( '../helpers/errorHandler' ) ,
77 {
88 retrieveParameters,
9- } = require ( '../helpers/userParamHelpers' ) ;
9+ } = require ( '../helpers/userParamHelpers' ) ,
10+ jsonstringify = require ( 'stringify-stream' ) ;
1011
1112
1213const listBoxes = async function listBoxes ( req , res , next ) {
13- try {
14- let boxes = await Box . find ( ) . exec ( ) ;
15- const users = await User . find ( ) . exec ( ) ;
16-
17- boxes = boxes
18- . map ( b => b . toJSON ( { includeSecrets : true } ) ) ;
19-
20- for ( const user of users ) {
21- for ( const userbox of user . boxes ) {
22- const foundbox = boxes . find ( box => box . _id . equals ( userbox ) ) ;
23- if ( foundbox ) {
24- foundbox . owner = user . toJSON ( { includeSecrets : true } ) ;
25- }
26- }
27- }
14+ // default format
15+ const stringifier = jsonstringify ( { open : '[' , close : ']' } ) ;
2816
29- res . send ( { code : 'Ok' , boxes } ) ;
17+ try {
18+ const stream = await Box . find ( { } , { _id : 1 , name : 1 , exposure : 1 , model : 1 , createdAt : 1 , updatedAt : 1 } ) . cursor ( { lean : true } ) ;
19+ stream
20+ . pipe ( stringifier )
21+ . on ( 'error' , function ( err ) {
22+ res . end ( `Error: ${ err . message } ` ) ;
23+ } )
24+ . pipe ( res ) ;
3025 } catch ( err ) {
3126 handleError ( err , next ) ;
3227 }
@@ -35,15 +30,10 @@ const listBoxes = async function listBoxes (req, res, next) {
3530const listUsers = async function listUsers ( req , res , next ) {
3631 try {
3732 const users = await User . find ( )
38- . populate ( 'boxes' )
3933 . then ( function ( users ) {
4034 return users . map ( function ( user ) {
41- const boxes = user . boxes . map ( b => b . toJSON ( { includeSecrets : true } ) ) ;
42-
4335 user = user . toJSON ( { includeSecrets : true } ) ;
4436
45- user . boxes = boxes ;
46-
4737 return user ;
4838 } ) ;
4939 } ) ;
0 commit comments