Skip to content

Commit 0b81a76

Browse files
committed
Fix loopbackio#1745 - dao coerces empty object into array
1 parent c7535ff commit 0b81a76

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

lib/dao.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1558,7 +1558,14 @@ function coerceArray(val) {
15581558
throw new Error(g.f('Value is not an {{array}} or {{object}} with sequential numeric indices'));
15591559
}
15601560

1561-
var arrayVal = new Array(Object.keys(val).length);
1561+
// It is an object, check if empty
1562+
var props = Object.keys(val);
1563+
1564+
if (props.length === 0) {
1565+
throw new Error(g.f('Value is an empty {{object}}'));
1566+
}
1567+
1568+
var arrayVal = new Array(props.length);
15621569
for (var i = 0; i < arrayVal.length; ++i) {
15631570
if (!val.hasOwnProperty(i)) {
15641571
throw new Error(g.f('Value is not an {{array}} or {{object}} with sequential numeric indices'));

test/loopback-dl.test.js

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1381,6 +1381,8 @@ describe('DataAccessObject', function() {
13811381
},
13821382
location: 'GeoPoint',
13831383
scores: [Number],
1384+
array: 'array',
1385+
object: 'object',
13841386
});
13851387
});
13861388

@@ -1638,7 +1640,7 @@ describe('DataAccessObject', function() {
16381640
assert(error, 'An error should have been thrown');
16391641
});
16401642

1641-
it('throws an error if the filter.limit property is nagative', function() {
1643+
it('throws an error if the filter.limit property is negative', function() {
16421644
try {
16431645
// The limit param must be a valid number
16441646
filter = model._normalize({limit: -1});
@@ -1719,6 +1721,18 @@ describe('DataAccessObject', function() {
17191721
assert.deepEqual(where, {date: undefined});
17201722
});
17211723

1724+
it('does not coerce empty objects to arrays', function() {
1725+
where = model._coerce({object: {}});
1726+
where.object.should.not.be.an.Array();
1727+
where.object.should.be.an.Object();
1728+
});
1729+
1730+
it('does not coerce an empty array', function() {
1731+
where = model._coerce({array: []});
1732+
where.array.should.be.an.Array();
1733+
where.array.should.have.length(0);
1734+
});
1735+
17221736
it('does not coerce to a number for a simple value that produces NaN', function() {
17231737
where = model._coerce({age: 'xyz'});
17241738
assert.deepEqual(where, {age: 'xyz'});

0 commit comments

Comments
 (0)