Skip to content

Commit

Permalink
fix: ensure props is object in entities #152
Browse files Browse the repository at this point in the history
  • Loading branch information
4lessandrodev committed May 2, 2024
1 parent 9cfb437 commit d8a6229
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions lib/core/entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ export class Entity<Props extends EntityProps> extends GettersAndSetters<Props>
protected autoMapper: AutoMapper<Props>;
constructor(props: Props, config?: ISettings) {
super(Object.assign({}, { createdAt: new Date(), updatedAt: new Date() }, { ...props }), 'Entity', config);
if (typeof props !== 'object' || (props instanceof Date) || Array.isArray(props)) {
throw new Error(`Props must be an 'object' for entities, but received: '${typeof props}' as props on Class '${this.constructor.name}'`);
};
const isID = this.validator.isID(props?.['id']);
const isStringOrNumber = this.validator.isString(props?.['id']) || this.validator.isNumber(props?.['id']);
this._id = isStringOrNumber ? ID.create(props?.['id']) : isID ? props?.['id'] : ID.create();
Expand Down Expand Up @@ -47,7 +50,7 @@ export class Entity<Props extends EntityProps> extends GettersAndSetters<Props>
toObject<T>(adapter?: IAdapter<this, T>)
: T extends {}
? T & EntityMapperPayload
: ReadonlyDeep<AutoMapperSerializer<Props> & EntityMapperPayload> {
: ReadonlyDeep<AutoMapperSerializer<Props> & EntityMapperPayload> {
if (adapter && typeof adapter?.build === 'function') return adapter.build(this).value() as any;

const serializedObject = this.autoMapper.entityToObj(this) as ReadonlyDeep<AutoMapperSerializer<Props>>;
Expand Down Expand Up @@ -91,12 +94,11 @@ export class Entity<Props extends EntityProps> extends GettersAndSetters<Props>
* @param props as optional Entity Props.
* @returns new Entity instance.
*/
clone(props?: Partial<Props>): this {
const _props = props ? { ...this.props, ...props } : { ...this.props };
clone(props?: Props extends object ? Partial<Props> : never): this {
const instance = Reflect.getPrototypeOf(this);
const _props = props ? { ...this.props, ...props } : { ...this.props };
const args = [_props, this.config];
const entity = Reflect.construct(instance!.constructor, args);
return entity
return Reflect.construct(instance!.constructor, args);
}

/**
Expand Down

0 comments on commit d8a6229

Please sign in to comment.