techfort / LokiJS

javascript embeddable / in-memory database
http:/techfort.github.io/LokiJS
MIT License
6.73k stars 482 forks source link

add collection option (disableFreeze) to will freeze all objects in a collection #836

Closed kavaro closed 4 years ago

kavaro commented 4 years ago

High level goal

I would like to use loki as a data store for my react applications. Given react works best with immutable data, the idea is to have an option on Collection that will ensure all documents stored in that collection, emitted by that collection and returned from that collection are immutable. Only the documents are immutable, the internal data array(s) are not, as it is quite easy to slice those whenever a something changed (for example on a rebuild event). The goal is to make loki compatible with typical react tools, like immer and redux, that help manage immutable data. Hopefully, this can help proliferate loki in the react community.

Implementation

The disableFreeze option will freeze all documents inserted/updated and removed from the collection. Furthermore dynamicViews will freeze filterPipeline and simpleSort and sortCriteria. DynamicView will emit a 'filter' event when the filter has changed and a 'sort' event when the sort has changed.

Testing

I have added a tests that cover the full functionality in specs/immutable.spec.js

Benchmarks

When disableFreeze is true, then there is no noticeable speed difference compared to master. When the user opts in to the immutability by setting disableFreeze to false, then there will obviously be a speed impact.

I hope this pull request makes sense. If you have any questions, please let me know.