Skip to content

Commit ac89e09

Browse files
committed
plain schema() definition: exclude parent props from initialize method
1 parent 1c31a8c commit ac89e09

File tree

3 files changed

+51
-3
lines changed

3 files changed

+51
-3
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@colyseus/schema",
3-
"version": "3.0.71",
3+
"version": "3.0.72",
44
"description": "Binary state serializer with delta encoding for games",
55
"bin": {
66
"schema-codegen": "bin/schema-codegen",

src/annotations.ts

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -637,14 +637,27 @@ export function schema<
637637
return defaults;
638638
};
639639

640+
const getParentProps = (props: any) => {
641+
const fieldNames = Object.keys(fields);
642+
const parentProps: any = {};
643+
for (const key in props) {
644+
if (!fieldNames.includes(key)) {
645+
parentProps[key] = props[key];
646+
}
647+
}
648+
return parentProps;
649+
}
650+
640651
/** @codegen-ignore */
641652
const klass = Metadata.setFields<any>(class extends (inherits as any) {
642653
constructor(...args: any[]) {
643-
super(Object.assign({}, getDefaultValues(), args[0] || {}));
644-
645654
// call initialize method
646655
if (methods.initialize && typeof methods.initialize === 'function') {
656+
super(Object.assign({}, getDefaultValues(), getParentProps(args[0] || {})));
647657
methods.initialize.apply(this, args);
658+
659+
} else {
660+
super(Object.assign({}, getDefaultValues(), args[0] || {}));
648661
}
649662
}
650663
}, fields) as SchemaWithExtendsConstructor<T, ExtractInitProps<T>, P>;

test/Definition.test.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -675,6 +675,41 @@ describe("Definition Tests", () => {
675675
});
676676
});
677677

678+
it("should exclude parent props from initialize method", () => {
679+
const StatSchema = schema({
680+
value: 'number',
681+
initialize(value: number) {
682+
this.value = value;
683+
},
684+
});
685+
686+
const EntitySchema = schema({
687+
id: 'string',
688+
initialize({ id }: any) {
689+
this.id = id;
690+
},
691+
});
692+
693+
const LivingEntitySchema = EntitySchema.extends({
694+
stats: { map: StatSchema },
695+
initialize(props: any) {
696+
EntitySchema.prototype.initialize.call(this, props);
697+
698+
for (const [key, value] of Object.entries(props.stats)) {
699+
this.stats.set(key, new StatSchema(value as number));
700+
}
701+
},
702+
});
703+
704+
const entity = new LivingEntitySchema({
705+
id: '123',
706+
stats: { hp: 500, },
707+
});
708+
709+
assert.strictEqual(entity.id, '123');
710+
assert.strictEqual(entity.stats.get('hp')?.value, 500);
711+
});
712+
678713
});
679714

680715
});

0 commit comments

Comments
 (0)