File tree Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change @@ -127,6 +127,8 @@ class Packer {
127127 this . packable ( x [ i ] === undefined ? null : x [ i ] , onError ) ( ) ;
128128 }
129129 }
130+ } else if ( isIterable ( x ) ) {
131+ return this . packableIterable ( x , onError ) ;
130132 } else if ( x instanceof Structure ) {
131133 var packableFields = [ ] ;
132134 for ( var i = 0 ; i < x . fields . length ; i ++ ) {
@@ -160,6 +162,16 @@ class Packer {
160162 }
161163 }
162164
165+ packableIterable ( iterable , onError ) {
166+ try {
167+ const array = Array . from ( iterable ) ;
168+ return this . packable ( array , onError ) ;
169+ } catch ( e ) {
170+ // handle errors from iterable to array conversion
171+ onError ( newError ( `Cannot pack given iterable, ${ e . message } : ${ iterable } ` ) ) ;
172+ }
173+ }
174+
163175 /**
164176 * Packs a struct
165177 * @param signature the signature of the struct
@@ -612,6 +624,13 @@ class Unpacker {
612624 }
613625}
614626
627+ function isIterable ( obj ) {
628+ if ( obj == null ) {
629+ return false ;
630+ }
631+ return typeof obj [ Symbol . iterator ] === 'function' ;
632+ }
633+
615634export {
616635 Packer ,
617636 Unpacker ,
Original file line number Diff line number Diff line change @@ -1040,6 +1040,38 @@ describe('session', () => {
10401040 testConnectionTimeout ( true , done ) ;
10411041 } ) ;
10421042
1043+ it ( 'should convert iterable to array' , done => {
1044+ const iterable = { } ;
1045+ iterable [ Symbol . iterator ] = function * ( ) {
1046+ yield '111' ;
1047+ yield '222' ;
1048+ yield '333' ;
1049+ } ;
1050+
1051+ session . run ( 'RETURN $array' , { array : iterable } ) . then ( result => {
1052+ const records = result . records ;
1053+ expect ( records . length ) . toEqual ( 1 ) ;
1054+ const received = records [ 0 ] . get ( 0 ) ;
1055+ expect ( received ) . toEqual ( [ '111' , '222' , '333' ] ) ;
1056+ done ( ) ;
1057+ } ) . catch ( error => {
1058+ done . fail ( error ) ;
1059+ } ) ;
1060+ } ) ;
1061+
1062+ it ( 'should fail to convert illegal iterable to array' , done => {
1063+ const iterable = { } ;
1064+ iterable [ Symbol . iterator ] = function ( ) {
1065+ } ;
1066+
1067+ session . run ( 'RETURN $array' , { array : iterable } ) . then ( result => {
1068+ done . fail ( 'Failre expected but query returned ' + JSON . stringify ( result . records [ 0 ] . get ( 0 ) ) ) ;
1069+ } ) . catch ( error => {
1070+ expect ( error . message . indexOf ( 'Cannot pack given iterable' ) ) . not . toBeLessThan ( 0 ) ;
1071+ done ( ) ;
1072+ } ) ;
1073+ } ) ;
1074+
10431075 function serverIs31OrLater ( done ) {
10441076 if ( serverVersion . compareTo ( VERSION_3_1_0 ) < 0 ) {
10451077 done ( ) ;
You can’t perform that action at this time.
0 commit comments