liuyg
2021-07-02 25ce610f6ecca7325e7a743dc032c4a76559c63d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
define(function() {
  //we don't use dojo's declare to define class
  //because this function will be used in node.js
 
  function BaseVersionManager(){
    /******************************************************
      element signature:
      {
        //the version you want to upgrade to. version format: 1.0.0
        version: '',
 
        //the version discription
        description: '',
 
        //the upgrade logic to upgrade from the latest old verion to this version
        //the first upgrader will upgrade unknow version to the first version
        upgrader: function(oldConfig){
          //your logic here
          return newConfig;
        }
      }
    ******************************************************/
    this.versions = [];
 
    this.upgrade = function(config, _oldVersion, _newVersion){
      //the config is the old version
      //method should return new upgraded config
      var oldVersionIndex = this.getVersionIndex(_oldVersion);
      var newVersionIndex = this.getVersionIndex(_newVersion);
 
      if(oldVersionIndex > newVersionIndex){
        throw Error('New version should higher than old version.');
      }
      var newConfig = config, i;
      for(i = oldVersionIndex + 1; i <= newVersionIndex; i++){
        if(!this.versions[i].upgrader){
          //if no upgrader, we consider the version is compatible
          continue;
        }
        newConfig = this.versions[i].upgrader(newConfig);
      }
      return newConfig;
    };
 
    this.getVersionIndex = function(_version){
      var version = this.fixVersion(_version);
      var versionIndex, i;
 
      for(i = 0; i < this.versions.length; i++){
        if(this.versions[i].version === version){
          versionIndex = i;
        }
      }
      //if there is no version, we assume it's very old and will upgrade from the first version
      if(version === null){
        versionIndex = -1;
      }
 
      if(versionIndex === undefined){
        //for unknown version, we assume it's the latest version but it's not in versions array.
        versionIndex = this.versions.length - 1;
      }
 
      return versionIndex;
    };
 
    this.fixVersion = function(version){
      if(!version){
        return null;
      }
      return version;
      //TODO
    };
  }
 
  return BaseVersionManager;
});