db.js 1.6 KB

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