Created
July 18, 2021 06:07
-
-
Save HallexCosta/7d9f1b5b3e77f5fab5a7b6dd20c4ad27 to your computer and use it in GitHub Desktop.
Best practices to create Entities
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export type Override<Original, Override> = Pick< | |
Original, | |
Exclude<keyof Original, keyof Override> | |
> & | |
Override; | |
type PartialEntity<T, K = Entity<T>> = Override<T, Partial<K>>; | |
abstract class Entity<EntityType> { | |
public readonly id: string; | |
public readonly created_at: Date; | |
public readonly updated_at: Date; | |
public constructor(props: PartialEntity<EntityType>) { | |
Object.assign(this, props); | |
if (!props.id) { | |
this.id = 'cc4ee979-8d1e-4ba3-9143-31bc6015b125'; | |
} | |
if (!props.created_at) { | |
this.created_at = new Date(); | |
} | |
if (!props.updated_at) { | |
this.updated_at = new Date(); | |
} | |
Object.freeze(this); | |
} | |
} | |
class Incident extends Entity<Incident> { | |
public readonly name: string; | |
public readonly description: string; | |
public readonly coast: number; | |
public constructor(props: PartialEntity<Incident>) { | |
super(props); | |
console.log(this); | |
} | |
} | |
new Incident({ | |
name: 'Dog', | |
coast: 1.7, | |
description: 'Dog' | |
}); | |
new Incident({ | |
id: '39b26e41-6462-4107-8e75-2a3042910a78', | |
name: 'Run over Cat', | |
description: 'The cat had an accident and was hit by a car', | |
coast: 500.4, | |
created_at: new Date('2020-05-02'), | |
updated_at: new Date('2020-07-24') | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment