Move CRUD logic to library and fix bugs