@@ -34,6 +34,7 @@ export type PartialIndex<I> = {
3434 * that return a properly typed output.
3535 */
3636export interface IStaticThis < I , T > {
37+ version : number ,
3738 // Todo: any should be I!
3839 indexType : { new ( ) : any } ,
3940
@@ -98,8 +99,13 @@ export default class ValidatedTopic {
9899 public static readonly indexType : any
99100 public static readonly vaults = { }
100101
102+ public static version = 0
103+ public static migrations = new Map < number , string > ( )
104+
101105 private static _className : string
102106
107+ public _version : number = 0
108+
103109 /**
104110 * Return the current class name
105111 *
@@ -161,6 +167,11 @@ export default class ValidatedTopic {
161167 instance . setState ( state )
162168 await instance . setIndex ( index )
163169
170+ /* istanbul ignore next */
171+ if ( ! instance . _version ) {
172+ instance . _version = this . version
173+ }
174+
164175 return instance
165176 }
166177
@@ -228,7 +239,10 @@ export default class ValidatedTopic {
228239 return undefined
229240 }
230241
231- return this . create ( state , index , data )
242+ const instance = await this . create ( state , index , data )
243+ await instance . migrate ( )
244+
245+ return instance
232246 } )
233247 }
234248
@@ -298,6 +312,8 @@ export default class ValidatedTopic {
298312 const index = queries [ i ] . index
299313 const instance = await this . create ( state , index as I , data )
300314
315+ await instance . migrate ( )
316+
301317 instances . push ( instance )
302318 }
303319
@@ -541,6 +557,38 @@ export default class ValidatedTopic {
541557 }
542558 }
543559
560+ /**
561+ * Migrate data using predefined migration methods
562+ */
563+ public async migrate ( ) {
564+ const type = this . constructor as typeof ValidatedTopic
565+ const { migrations } = type
566+
567+ let migrated = false
568+
569+ // tslint:disable-next-line:strict-type-predicates
570+ if ( this . _version === undefined ) {
571+ this . _version = 0
572+ }
573+
574+ if ( this . _version === type . version ) {
575+ return
576+ }
577+
578+ for ( const [ version , methodName ] of migrations . entries ( ) ) {
579+ if ( version > this . _version ) {
580+ const method = ( this as any ) [ methodName ]
581+ await method . call ( this )
582+ this . _version = version
583+ migrated = true
584+ }
585+ }
586+
587+ if ( migrated ) {
588+ await this . set ( )
589+ }
590+ }
591+
544592 /**
545593 * Throw a ValidateError including relevant details
546594 */
0 commit comments