db.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. const low = require('lowdb');
  2. const FileSync = require('lowdb/adapters/FileSync');
  3. const paths = require('../data/paths.json'); // get our paths
  4. const settings = require('../data/settings.json'); // get the settings
  5. const defaults = settings.defaults || {}; // load the defaults
  6. // connect the db from the path
  7. const connect = (dir, opts) => {
  8. let options = opts || Object.assign({}, defaults, paths[dir]); // baseline the options
  9. let adapter = new FileSync(options.database); // init the db adapter
  10. let db = low(adapter); // connect the db
  11. return db;
  12. };
  13. // find a file in the db
  14. const find = (db, file) => {
  15. return db
  16. .get('files')
  17. .find({
  18. input: file,
  19. })
  20. .value(); // does it already exist?
  21. };
  22. // set a file in the db
  23. const set = async (db, file, payload) => {
  24. if (!payload && typeof file === 'object') {
  25. db.get('files').push(file).write();
  26. return file;
  27. }
  28. return db
  29. .get('files')
  30. .find({
  31. input: file,
  32. })
  33. .assign(payload)
  34. .write();
  35. };
  36. // remove a file from the db
  37. const remove = async (db, file) => {
  38. return db
  39. .get('files')
  40. .remove({
  41. input: file,
  42. })
  43. .write(); // remove file from database
  44. };
  45. module.exports = {
  46. connect,
  47. find,
  48. remove,
  49. set
  50. };