Skip to content

Commit

Permalink
fix: @column() should not tamper parent attributes directly (#362)
Browse files Browse the repository at this point in the history
  • Loading branch information
cyjake authored Oct 25, 2022
1 parent 111105f commit e43fe1a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/decorators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,16 @@ export function Column(options: ColumnOption | DATA_TYPE<DataType> | DataType =

// target refers to model prototype, an internal instance of `Bone {}`
const model = target.constructor as any;
const { attributes = (model.attributes = {}) } = model;
if (!Object.hasOwnProperty('attributes') || !model.attributes) {
Object.defineProperty(model, 'attributes', {
value: { ...model.attributes },
writable: false,
enumerable: false,
configurable: true,
});
}
const { name: columnName, ...restOptions } = options;
attributes[propertyKey] = { ...restOptions, columnName };
model.attributes[propertyKey] = { ...restOptions, columnName };
};
}

Expand Down
29 changes: 29 additions & 0 deletions test/types/decorators.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,35 @@ describe('=> Decorators (TypeScript)', function() {
assert.equal((description as AttributeMeta).toSqlString!(), '`description` VARCHAR(64)');
assert.equal((status as AttributeMeta).toSqlString!(), '`status` INTEGER(2) UNSIGNED');
});

it('should not override attributes of parent class', async function() {
class Base extends Bone {
@Column()
id: bigint;
}

class Note extends Base {
@Column()
body: string;
}

class Comment extends Base {
@Column()
body: string;

@Column()
targetType: string;

@Column()
targetId: bigint;
}
await Note.sync({ force: true });
await Comment.sync({ force: true });

assert.deepEqual(Object.keys(Base.attributes), ['id']);
assert.deepEqual(Object.keys(Note.attributes), ['id', 'body']);
assert.deepEqual(Object.keys(Comment.attributes), ['id', 'body', 'targetType', 'targetId']);
});
});

describe('=> @HasMany()', function() {
Expand Down

0 comments on commit e43fe1a

Please sign in to comment.