SerializerLeveldb.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. const _level = require('level');
  2. const promisify = require('./util/promisify');
  3. const level = promisify(_level);
  4. class LevelDbSerializer {
  5. constructor({ cacheDirPath }) {
  6. this.path = cacheDirPath;
  7. this.leveldbLock = Promise.resolve();
  8. }
  9. read() {
  10. const start = Date.now();
  11. const moduleCache = {};
  12. return level(this.path)
  13. .then(
  14. db =>
  15. new Promise((resolve, reject) => {
  16. const dbClose = promisify(db.close, { context: db });
  17. db.createReadStream()
  18. .on('data', data => {
  19. const value = data.value;
  20. if (!moduleCache[data.key]) {
  21. moduleCache[data.key] = value;
  22. }
  23. })
  24. .on('end', () => {
  25. dbClose().then(resolve, reject);
  26. });
  27. }),
  28. )
  29. .then(() => moduleCache);
  30. }
  31. write(moduleOps) {
  32. const ops = moduleOps;
  33. if (ops.length === 0) {
  34. return Promise.resolve();
  35. }
  36. for (let i = 0; i < ops.length; i++) {
  37. if (ops[i].value === null) {
  38. ops[i].type = 'delete';
  39. } else {
  40. if (typeof ops[i].value !== 'string') {
  41. ops[i].value = JSON.stringify(ops[i].value);
  42. }
  43. ops[i].type = 'put';
  44. }
  45. }
  46. const cachePath = this.path;
  47. return (this.leveldbLock = this.leveldbLock
  48. .then(() => level(cachePath))
  49. .then(db => promisify(db.batch, { context: db })(ops).then(() => db))
  50. .then(db => promisify(db.close, { context: db })()));
  51. }
  52. }
  53. module.exports = LevelDbSerializer;