Created
January 8, 2020 09:39
-
-
Save ybouhjira/0285a6b714d286c3350c1a8c232b9746 to your computer and use it in GitHub Desktop.
AbstractStore.ts
This file contains 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
import cloneDeep from 'lodash.clonedeep'; | |
import * as shortId from 'shortid'; | |
export abstract class AbstractStore<T> { | |
private entities: Map<string, T> = new Map(); | |
create(data: T): T { | |
const entity = cloneDeep(data); | |
entity.id = shortId.generate(); | |
this.entities.set(entity.id, entity); | |
return entity; | |
} | |
delete(id: string): boolean { | |
return this.entities.delete(id); | |
} | |
update(entity: T): boolean { | |
const entityWithId = entity as any; | |
if (this.entities.has(entityWithId.id)) { | |
this.entities.set(entityWithId.id, cloneDeep(entity)); | |
return true; | |
} else { | |
return false; | |
} | |
} | |
get(id: string): T { | |
return cloneDeep(this.entities.get(id)); | |
} | |
getAll(): T[] { | |
return cloneDeep(this.entities.values()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment