File tree 2 files changed +51
-0
lines changed
2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change @@ -127,6 +127,8 @@ class Packer {
127
127
this . packable ( x [ i ] === undefined ? null : x [ i ] , onError ) ( ) ;
128
128
}
129
129
}
130
+ } else if ( isIterable ( x ) ) {
131
+ return this . packableIterable ( x , onError ) ;
130
132
} else if ( x instanceof Structure ) {
131
133
var packableFields = [ ] ;
132
134
for ( var i = 0 ; i < x . fields . length ; i ++ ) {
@@ -160,6 +162,16 @@ class Packer {
160
162
}
161
163
}
162
164
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
+
163
175
/**
164
176
* Packs a struct
165
177
* @param signature the signature of the struct
@@ -612,6 +624,13 @@ class Unpacker {
612
624
}
613
625
}
614
626
627
+ function isIterable ( obj ) {
628
+ if ( obj == null ) {
629
+ return false ;
630
+ }
631
+ return typeof obj [ Symbol . iterator ] === 'function' ;
632
+ }
633
+
615
634
export {
616
635
Packer ,
617
636
Unpacker ,
Original file line number Diff line number Diff line change @@ -1040,6 +1040,38 @@ describe('session', () => {
1040
1040
testConnectionTimeout ( true , done ) ;
1041
1041
} ) ;
1042
1042
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
+
1043
1075
function serverIs31OrLater ( done ) {
1044
1076
if ( serverVersion . compareTo ( VERSION_3_1_0 ) < 0 ) {
1045
1077
done ( ) ;
You can’t perform that action at this time.
0 commit comments