Created
September 10, 2020 16:27
-
-
Save YannickFricke/b3b45c1b1f18586c4d0ae94792cd9ef0 to your computer and use it in GitHub Desktop.
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
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