Skip to content

Commit

Permalink
fix: object results should have attribute values casted as well (#433)
Browse files Browse the repository at this point in the history
  • Loading branch information
cyjake authored Feb 10, 2025
1 parent df1d77a commit 6640ada
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 20 deletions.
6 changes: 5 additions & 1 deletion src/bone.js
Original file line number Diff line number Diff line change
Expand Up @@ -1194,7 +1194,11 @@ class Bone {
for (const key in data) {
const value = data[key];
const attribute = attributeMap[key];
result[attribute ? attribute.name : key] = value;
if (attribute) {
result[attribute.name] = attribute.cast(value);
} else {
result[key] = value;
}
}
return result;
}
Expand Down
47 changes: 28 additions & 19 deletions test/integration/suite/json.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,29 +7,28 @@ const { Bone, Raw } = require('../../../src');

describe('=> Basic', () => {

describe('=> JSON Functions', ()=>{

class Gen extends Bone { }
Gen.init({
id: { type: Bone.DataTypes.INTEGER, primaryKey: true },
name: Bone.DataTypes.STRING,
extra: Bone.DataTypes.JSONB,
deletedAt: Bone.DataTypes.DATE,
});
class Gen extends Bone { }
Gen.init({
id: { type: Bone.DataTypes.INTEGER, primaryKey: true },
name: Bone.DataTypes.STRING,
extra: Bone.DataTypes.JSONB,
deletedAt: Bone.DataTypes.DATE,
});

before(async () => {
await Bone.driver.dropTable('gens');
await Gen.sync();
});
before(async () => {
await Bone.driver.dropTable('gens');
await Gen.sync();
});

after(async () => {
await Bone.driver.dropTable('gens');
});
after(async () => {
await Bone.driver.dropTable('gens');
});

beforeEach(async () => {
await Gen.remove({}, true);
});
beforeEach(async () => {
await Gen.remove({}, true);
});

describe('=> JSON Functions', () => {
it('bone.jsonMerge(name, value, options) should still update if currently NULL', async () => {
const gen = await Gen.create({ name: '章3️⃣疯' });
assert.equal(gen.name, '章3️⃣疯');
Expand Down Expand Up @@ -139,4 +138,14 @@ describe('=> Basic', () => {
assert.deepEqual(gen.extra.a, [3, 4]);
});
});

describe('=> JSONB value handling', () => {
it('should still be able to return JSON object if named column exists', async () => {
await Gen.create({ name: '章3️⃣疯', extra: { a: 1 } });
const [result] = await Gen.select("JSON_EXTRACT(extra, '$.a') as a", 'extra');
// extracted prop returns string in mysql but number in mysql2
assert.equal(Number(result.a), 1);
assert.deepEqual(result.extra, { a: 1 });
});
});
});

0 comments on commit 6640ada

Please sign in to comment.