main.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. var lodash = require('lodash');
  3. var isPromise = require('is-promise');
  4. module.exports = function (adapter) {
  5. if (typeof adapter !== 'object') {
  6. throw new Error('An adapter must be provided, see https://github.com/typicode/lowdb/#usage');
  7. }
  8. // Create a fresh copy of lodash
  9. var _ = lodash.runInContext();
  10. var db = _.chain({});
  11. // Add write function to lodash
  12. // Calls save before returning result
  13. _.prototype.write = _.wrap(_.prototype.value, function (func) {
  14. var funcRes = func.apply(this);
  15. return db.write(funcRes);
  16. });
  17. function plant(state) {
  18. db.__wrapped__ = state;
  19. return db;
  20. }
  21. // Lowdb API
  22. // Expose _ for mixins
  23. db._ = _;
  24. db.read = function () {
  25. var r = adapter.read();
  26. return isPromise(r) ? r.then(plant) : plant(r);
  27. };
  28. db.write = function (returnValue) {
  29. var w = adapter.write(db.getState());
  30. return isPromise(w) ? w.then(function () {
  31. return returnValue;
  32. }) : returnValue;
  33. };
  34. db.getState = function () {
  35. return db.__wrapped__;
  36. };
  37. db.setState = function (state) {
  38. return plant(state);
  39. };
  40. return db.read();
  41. };