Skip to content

Commit 743b50b

Browse files
authored
Merge pull request #141 from pmndrs/feat/constraint-schemas
feat: constrain trait schemas to no longer accept object or array literals
2 parents 5369f36 + 0a18093 commit 743b50b

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

packages/core/src/trait/trait.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,16 @@ import {
1414
createSetFunction,
1515
} from './utils/create-accessors';
1616
import { createStore } from './utils/create-store';
17+
import { validateSchema } from './utils/validate-schema';
1718

1819
let traitId = 0;
1920

2021
function defineTrait<S extends Schema>(schema: S = {} as S): Trait<Norm<S>> {
2122
const isAoS = typeof schema === 'function';
2223
const traitType: TraitType = isAoS ? 'aos' : 'soa';
2324

25+
validateSchema(schema);
26+
2427
const Trait = Object.assign((params: Partial<Norm<S>>) => [Trait, params], {
2528
schema: schema as Norm<S>,
2629
[$internal]: {
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { Schema } from '../types';
2+
3+
export function validateSchema(schema: Schema) {
4+
for (const key in schema) {
5+
const value = schema[key as keyof Schema];
6+
if (value !== null && typeof value === 'object') {
7+
const kind = Array.isArray(value) ? 'array' : 'object';
8+
throw new Error(`Koota: ${key} is an ${kind}, which is not supported in traits.`);
9+
}
10+
}
11+
}

packages/core/tests/trait.test.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,13 @@ describe('Trait', () => {
2929
expect(typeof Test === 'function').toBe(true);
3030
});
3131

32+
it('should throw an error if the schema contains an object or array', () => {
33+
// @ts-expect-error - we want to test the error case
34+
expect(() => trait({ object: { a: 1, b: 2 } })).toThrow();
35+
// @ts-expect-error - we want to test the error case
36+
expect(() => trait({ array: [1, 2, 3] })).toThrow();
37+
});
38+
3239
it('should add and remove traits to an entity', () => {
3340
const entity = world.spawn();
3441

0 commit comments

Comments
 (0)