storage.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. 'use strict';
  2. const path = require('path');
  3. const lowdb = require('lowdb');
  4. const FileSync = require('lowdb/adapters/FileSync');
  5. const fs = require('fs');
  6. const getPort = require('get-port');
  7. const utils = require('../app/utils/utils');
  8. const config = require('./config');
  9. const storageDir = path.normalize('./storage/');
  10. exports.setup = function () {
  11. if (!fs.existsSync(storageDir)) {
  12. utils.mkdir(storageDir);
  13. utils.chmodPath(storageDir, '777');
  14. }
  15. const file = storageDir + 'db.json';
  16. const adapter = new FileSync(file);
  17. const db = lowdb(adapter);
  18. if (!db.has('egg_config').value()) {
  19. db.set('egg_config', {}).write();
  20. }
  21. return true;
  22. };
  23. exports.instance = function (file = null) {
  24. if (!file) {
  25. file = path.normalize('./storage/db.json');
  26. }
  27. const isExist = fs.existsSync(file);
  28. if (!isExist) {
  29. return null;
  30. }
  31. const adapter = new FileSync(file);
  32. const db = lowdb(adapter);
  33. return db;
  34. };
  35. exports.getEggConfig = function () {
  36. const res = this.instance()
  37. .get('egg_config')
  38. .value();
  39. return res;
  40. };
  41. exports.setDynamicPort = async function () {
  42. // const eggConfig = config.get('egg');
  43. // console.log('setDynamicPort eggConfig:', eggConfig);
  44. // const dynamicPort = await getPort({port: eggConfig.port})
  45. const dynamicPort = await getPort();
  46. const res = this.instance()
  47. .set('egg_config.port', dynamicPort)
  48. .write();
  49. return res;
  50. };
  51. exports = module.exports;