config.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { debug } from '../lib/logger'
  2. import {
  3. resolvePath,
  4. readFile,
  5. writeFile,
  6. prettyLog,
  7. deepMerge
  8. } from '../lib/util'
  9. export type RecordMate = {
  10. /**
  11. * The hosts that have generated certificate
  12. */
  13. hosts: string[]
  14. /**
  15. * file hash
  16. */
  17. hash?: RecordHash
  18. }
  19. export type RecordHash = {
  20. key?: string
  21. cert?: string
  22. }
  23. const CONFIG_FILE_NAME = 'config.json'
  24. const CONFIG_FILE_PATH = resolvePath(CONFIG_FILE_NAME)
  25. class Config {
  26. /**
  27. * The mkcert version
  28. */
  29. private version: string | undefined
  30. private record: RecordMate | undefined
  31. public async init() {
  32. const str = await readFile(CONFIG_FILE_PATH)
  33. const options = str ? JSON.parse(str) : undefined
  34. if (options) {
  35. this.version = options.version
  36. this.record = options.record
  37. }
  38. }
  39. private async serialize() {
  40. await writeFile(CONFIG_FILE_PATH, prettyLog(this))
  41. }
  42. // deep merge
  43. public async merge(obj: Record<string, any>) {
  44. const currentStr = prettyLog(this)
  45. deepMerge(this, obj)
  46. const nextStr = prettyLog(this)
  47. debug(
  48. `Receive parameter ${prettyLog(
  49. obj
  50. )}, then update config from ${currentStr} to ${nextStr}`
  51. )
  52. await this.serialize()
  53. }
  54. public getRecord() {
  55. return this.record
  56. }
  57. public getVersion() {
  58. return this.version
  59. }
  60. }
  61. export default Config