Skip to content
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

fix: object results should have attribute values casted as well #433

Merged
merged 1 commit into from
Feb 10, 2025
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
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 });
});
});
});