db.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. const fs = require('fs');
  2. const Q = require('bluebird');
  3. const Loki = require('lokijs');
  4. const Settings = require('./settings');
  5. const log = require('./utils/logger').create('Db');
  6. let db;
  7. exports.init = () => {
  8. const filePath = Settings.dbFilePath;
  9. return Q.try(() => {
  10. // if db file doesn't exist then create it
  11. try {
  12. log.debug(`Check that db exists and it's writeable: ${filePath}`);
  13. fs.accessSync(filePath, fs.R_OK | fs.W_OK);
  14. return Q.resolve();
  15. } catch (err) {
  16. log.info(`Creating db: ${filePath}`);
  17. const tempdb = new Loki(filePath, {
  18. env: 'NODEJS',
  19. autoload: false
  20. });
  21. return new Q.promisify(tempdb.saveDatabase, { context: tempdb })();
  22. }
  23. }).then(() => {
  24. log.info(`Loading db: ${filePath}`);
  25. return new Q((resolve, reject) => {
  26. db = new Loki(filePath, {
  27. env: 'NODEJS',
  28. autosave: true,
  29. autosaveInterval: 5000,
  30. autoload: true,
  31. autoloadCallback(err) {
  32. if (err) {
  33. log.error(err);
  34. reject(new Error('Error instantiating db'));
  35. }
  36. resolve();
  37. }
  38. });
  39. });
  40. });
  41. };
  42. exports.getCollection = name => {
  43. if (!db.getCollection(name)) {
  44. db.addCollection(name, {
  45. unique: ['_id']
  46. });
  47. }
  48. return db.getCollection(name);
  49. };
  50. exports.close = () => {
  51. return new Q((resolve, reject) => {
  52. db.close(err => {
  53. if (err) {
  54. reject(err);
  55. } else {
  56. resolve();
  57. }
  58. });
  59. });
  60. };