You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.2 KiB

  1. import { loadEnv } from "@build/utils";
  2. import { LocalStorage, LowSync } from "lowdb";
  3. import { chain, cloneDeep } from "lodash-es";
  4. import { storageLocal } from ".";
  5. import { cookies } from "./cookie";
  6. type Data = {
  7. database: {};
  8. sys: {};
  9. };
  10. /**
  11. * db , LocalStorage存储
  12. */
  13. class DB {
  14. private db: LowSync<Data>;
  15. private static env = loadEnv();
  16. constructor() {
  17. this.db = new LowSync<Data>(
  18. new LocalStorage<Data>(`${DB.env.VITE_TITLE}-${DB.env.VITE_VERSION}`)
  19. );
  20. this.initialization();
  21. // @ts-ignore
  22. this.db.chain = chain(this.db.data);
  23. }
  24. private initialization() {
  25. this.db.data = storageLocal.getItem(
  26. `${DB.env.VITE_TITLE}-${DB.env.VITE_VERSION}`
  27. ) || { database: {}, sys: {} };
  28. this.db.write();
  29. }
  30. /**
  31. *
  32. * @param param0
  33. * @returns path
  34. */
  35. pathInit({
  36. dbName = "database",
  37. path = "",
  38. user = true,
  39. validator = () => true,
  40. defaultValue = ""
  41. }): string {
  42. const uuid = cookies.get("uuid") || "ghost-uuid";
  43. const currentPath = `${dbName}.${user ? `user.${uuid}` : "public"}${
  44. path ? `.${path}` : ""
  45. }`;
  46. // @ts-ignore
  47. const value = this.db.chain.get(currentPath).value();
  48. // @ts-ignore
  49. if (!(value !== undefined && validator(value))) {
  50. // @ts-ignore
  51. this.db.chain.set(currentPath, defaultValue).value();
  52. this.db.write();
  53. }
  54. return currentPath;
  55. }
  56. /**
  57. * |
  58. *
  59. * dbName.path = value
  60. * @param param0
  61. */
  62. dbSet({ dbName = "database", path = "", value = "", user = false }): void {
  63. const currentPath = this.pathInit({
  64. dbName,
  65. path,
  66. user
  67. });
  68. // @ts-ignore
  69. this.db.chain.set(currentPath, value).value();
  70. this.db.write();
  71. }
  72. /**
  73. *
  74. *
  75. * dbName.path || defaultValue
  76. * @param param0
  77. * @returns
  78. */
  79. dbGet({
  80. dbName = "database",
  81. path = "",
  82. defaultValue = "",
  83. user = false
  84. }): any {
  85. // @ts-ignore
  86. const values = this.db.chain
  87. .get(this.pathInit({ dbName, path, user, defaultValue }))
  88. .value();
  89. return cloneDeep(values);
  90. }
  91. }
  92. export const db = new DB();