Browse Source

docs: fix cfgmgr example

Sven 1 year ago
parent
commit
73391438fa
2 changed files with 7 additions and 4 deletions
  1. 4 1
      README.md
  2. 3 3
      lib/config.ts

+ 4 - 1
README.md

@@ -547,6 +547,8 @@ interface MyConfig {
 const defaultConfig: MyConfig = {
   foo: "hello",
   bar: 42,
+  baz: "xyz",
+  qux: "something",
 };
 /** If any properties are added to, removed from or renamed in MyConfig, increment this number */
 const formatVersion = 2;
@@ -587,7 +589,8 @@ const configMgr = new ConfigManager({
 /** Entrypoint of the userscript */
 async function init() {
   // wait for the config to be loaded from persistent storage
-  // if no data is saved in persistent storage yet or getData() is called before loadData(), the value of options.defaultConfig will be returned
+  // if no data was saved in persistent storage before or getData() is called before loadData(), the value of options.defaultConfig will be returned
+  // if the previously saved data needs to be migrated to a newer version, it will happen in this function call
   const configData = await configMgr.loadData();
 
   console.log(configData.foo); // "hello"

+ 3 - 3
lib/config.ts

@@ -80,7 +80,7 @@ export class ConfigManager<TData = any> {
 
       let parsed = JSON.parse(gmData);
 
-      if(gmFmtVer < this.formatVersion)
+      if(gmFmtVer < this.formatVersion && this.migrations)
         parsed = await this.runMigrations(parsed, gmFmtVer);
 
       return this.cachedConfig = typeof parsed === "object" ? parsed : undefined;
@@ -129,11 +129,11 @@ export class ConfigManager<TData = any> {
 
   /** Runs all necessary migration functions consecutively - may be overwritten in a subclass */
   protected async runMigrations(oldData: any, oldFmtVer: number): Promise<TData> {
-    console.info("#DEBUG - RUNNING MIGRATIONS", oldFmtVer, "->", this.formatVersion, "- oldData:", oldData);
-
     if(!this.migrations)
       return oldData as TData;
 
+    console.info("#DEBUG - RUNNING MIGRATIONS", oldFmtVer, "->", this.formatVersion, "- oldData:", oldData);
+
     // TODO: verify
     let newData = oldData;
     const sortedMigrations = Object.entries(this.migrations)