db.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. const level = require('level');
  2. const sub = require('level-sublevel');
  3. const search = require('level-search');
  4. class Database {
  5. constructor(){
  6. console.log("Constructing database!")
  7. this.db = sub(level("./database/mafaldadb", {valueEncoding: 'json'}));
  8. this.index = search(this.db, 'search');
  9. }
  10. open(callback){
  11. return this.db.open(callback);
  12. }
  13. close(callback){
  14. return this.db.close(callback);
  15. }
  16. put(key, value){
  17. return new Promise( (res,rej) => {
  18. this.db.put(key, value, (err,values) => {
  19. if(err)
  20. return rej(err);
  21. return res(values);
  22. });
  23. });
  24. }
  25. get(key){
  26. return new Promise( (res,rej) => {
  27. this.db.get(key, (err,values) => {
  28. if(err)
  29. return rej(err);
  30. return res(values);
  31. });
  32. });
  33. }
  34. del(key, options, callback){
  35. return this.db.del(key, options, callback);
  36. }
  37. batch(array, options, callback){
  38. return this.db.batch(array, options, callback);
  39. }
  40. isOpen(){
  41. return this.db.isOpen();
  42. }
  43. isClosed(){
  44. return this.db.isClosed();
  45. }
  46. createReadStream(options){
  47. return this.db.createReadStream(options);
  48. }
  49. createKeyStream(options){
  50. return this.db.createKeyStream(options);
  51. }
  52. createValueStream(options){
  53. return this.db.createValueStream(options);
  54. }
  55. createSearchStream(keys, options){
  56. return this.index.createSearchStream(keys, options);
  57. }
  58. };
  59. let database = null;
  60. function getSingleton() {
  61. return database = (database === null ? new Database() : database);
  62. }
  63. module.exports = getSingleton();