Skip to content

Convert iterable to array for query parameters #346

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 9, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/v1/internal/packstream-v1.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,8 @@ class Packer {
this.packable(x[i] === undefined ? null : x[i], onError)();
}
}
} else if (isIterable(x)) {
return this.packableIterable(x, onError);
} else if (x instanceof Structure) {
var packableFields = [];
for (var i = 0; i < x.fields.length; i++) {
Expand Down Expand Up @@ -160,6 +162,16 @@ class Packer {
}
}

packableIterable(iterable, onError) {
try {
const array = Array.from(iterable);
return this.packable(array, onError);
} catch (e) {
// handle errors from iterable to array conversion
onError(newError(`Cannot pack given iterable, ${e.message}: ${iterable}`));
}
}

/**
* Packs a struct
* @param signature the signature of the struct
Expand Down Expand Up @@ -612,6 +624,13 @@ class Unpacker {
}
}

function isIterable(obj) {
if (obj == null) {
return false;
}
return typeof obj[Symbol.iterator] === 'function';
}

export {
Packer,
Unpacker,
Expand Down
32 changes: 32 additions & 0 deletions test/v1/session.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1040,6 +1040,38 @@ describe('session', () => {
testConnectionTimeout(true, done);
});

it('should convert iterable to array', done => {
const iterable = {};
iterable[Symbol.iterator] = function* () {
yield '111';
yield '222';
yield '333';
};

session.run('RETURN $array', {array: iterable}).then(result => {
const records = result.records;
expect(records.length).toEqual(1);
const received = records[0].get(0);
expect(received).toEqual(['111', '222', '333']);
done();
}).catch(error => {
done.fail(error);
});
});

it('should fail to convert illegal iterable to array', done => {
const iterable = {};
iterable[Symbol.iterator] = function () {
};

session.run('RETURN $array', {array: iterable}).then(result => {
done.fail('Failre expected but query returned ' + JSON.stringify(result.records[0].get(0)));
}).catch(error => {
expect(error.message.indexOf('Cannot pack given iterable')).not.toBeLessThan(0);
done();
});
});

function serverIs31OrLater(done) {
if (serverVersion.compareTo(VERSION_3_1_0) < 0) {
done();
Expand Down