storage.js 1.4 KB

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