db.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. class Database {
  7. constructor(){
  8. console.log("Constructing database!")
  9. this.db = sub(level(DIR + "/mafaldadb", {valueEncoding: 'json'}));
  10. this.index = search(this.db, 'search');
  11. // this.createSearchStream = this.createSearchStream.bind(this);
  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. const results = [];
  51. return new Promise((res,rej) => {
  52. this.db.createReadStream(options)
  53. .on('data', function (data) {
  54. results.push(data.value);
  55. })
  56. .on('error', function (err) {
  57. rej(err);
  58. })
  59. .on('close', function () {
  60. })
  61. .on('end', function () {
  62. res(results);
  63. });
  64. });
  65. }
  66. createKeyStream(options){
  67. return this.db.createKeyStream(options);
  68. }
  69. createValueStream(options){
  70. return this.db.createValueStream(options);
  71. }
  72. createSearchStream(keys, options) {
  73. const results = [];
  74. return new Promise((res,rej) => {
  75. this.index.createSearchStream(keys,options)
  76. .on('data', function (data) {
  77. results.push(data.value);
  78. })
  79. .on('error', function (err) {
  80. rej(err);
  81. })
  82. .on('close', function () {
  83. })
  84. .on('end', function () {
  85. res(results);
  86. });
  87. });
  88. }
  89. read(options) {
  90. return this.createReadStream(options);
  91. }
  92. search(keys, options) {
  93. return this.createSearchStream(keys, options);
  94. }
  95. };
  96. let database = null;
  97. function getSingleton() {
  98. return database = (database === null ? new Database() : database);
  99. }
  100. module.exports = getSingleton();