Skip to content

Instantly share code, notes, and snippets.

@ybouhjira
Created January 8, 2020 09:39
Show Gist options
  • Save ybouhjira/0285a6b714d286c3350c1a8c232b9746 to your computer and use it in GitHub Desktop.
Save ybouhjira/0285a6b714d286c3350c1a8c232b9746 to your computer and use it in GitHub Desktop.
AbstractStore.ts
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