Skip to content

Instantly share code, notes, and snippets.

@YannickFricke
Created September 10, 2020 16:27
Show Gist options
  • Save YannickFricke/b3b45c1b1f18586c4d0ae94792cd9ef0 to your computer and use it in GitHub Desktop.
Save YannickFricke/b3b45c1b1f18586c4d0ae94792cd9ef0 to your computer and use it in GitHub Desktop.
import { Identifiable } from '@applier/framework/dist/definitions/Identifiable';
import { v4 } from 'uuid';
import { IRepository } from '@applier/framework/dist/definitions/IRepository';
export const useRepository = <T extends Identifiable>(entities: T[], setEntities: (newValues: T[]) => void): IRepository<T> => {
return {
getAll: function() {
return entities;
},
insert: function(entity: T) {
if (entity.id !== '') {
throw new Error('The entity already has an id. Please use the update method instead.');
}
let newEntity = {
...entity,
id: v4(),
};
setEntities([
...entities,
newEntity,
]);
return newEntity;
},
findOne: function(id: string) {
return entities.find(entity => entity.id === id);
},
findBy: function(props) {
return entities.filter(
(entity: T) => Object.keys(props).every(
(key) => entity[key as keyof T] === props[key as keyof T],
),
);
},
findOneBy: function(props) {
return this.findBy(props)[0];
},
update: function(id, newValues) {
setEntities(entities.map(entity => {
if (entity.id !== id) {
return entity;
}
return {
...entity,
...newValues,
};
}));
},
remove: function(id: string) {
setEntities(entities.filter(entity => entity.id !== id));
},
clear: function() {
setEntities([]);
},
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment