Skip to content

Commit

Permalink
feat(storage-engine): migrate old storages
Browse files Browse the repository at this point in the history
  • Loading branch information
alimd committed Jan 13, 2023
1 parent 146b9eb commit 10fc378
Showing 1 changed file with 31 additions and 10 deletions.
41 changes: 31 additions & 10 deletions core/storage-engine/src/storage-engine.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import {resolve} from 'node:path';

import {createLogger, globalAlwatr} from '@alwatr/logger';
import {createLogger, globalAlwatr, type AlwatrLogger} from '@alwatr/logger';
import {type AlwatrDocumentStorage, type AlwatrDocumentObject} from '@alwatr/type';
import exitHook from 'exit-hook';

import {type AlwatrStorageEngineConfig} from './type.js';
import {readJsonFile, writeJsonFile} from './util.js';

import type {AlwatrStorageEngineConfig} from './type.js';
import type {AlwatrLogger} from '@alwatr/logger';
import type {AlwatrDocumentStorage, AlwatrDocumentObject} from '@alwatr/type';

export type {AlwatrDocumentObject, AlwatrDocumentStorage};
export {type AlwatrDocumentObject, type AlwatrDocumentStorage};

globalAlwatr.registeredList.push({
name: '@alwatr/storage-engine',
Expand Down Expand Up @@ -71,7 +69,7 @@ globalAlwatr.registeredList.push({
* ```
*/
export class AlwatrStorageEngine<DocumentType extends AlwatrDocumentObject = AlwatrDocumentObject> {
static readonly formatVersion = 4;
static readonly formatVersion = 5;

/**
* Storage name like database table name.
Expand Down Expand Up @@ -157,6 +155,10 @@ export class AlwatrStorageEngine<DocumentType extends AlwatrDocumentObject = Alw

exitHook(this.forceSave);
this._storage = this.load();

if (this._storage.meta?.formatVersion !== AlwatrStorageEngine.formatVersion) {
this._migrateStorage();
}
}

/**
Expand All @@ -179,12 +181,31 @@ export class AlwatrStorageEngine<DocumentType extends AlwatrDocumentObject = Alw
throw new Error('invalid_storage_data');
}

if (storage.meta?.formatVersion !== AlwatrStorageEngine.formatVersion) {
this._logger.error('load', 'storage_version_incompatible', {storageMeta: storage.meta});
return storage;
}

protected _migrateStorage(): void {
if (this._storage.meta == null) {
this._storage.meta = {
id: this.name,
formatVersion: 5,
reversion: 0,
lastUpdated: Date.now(),
lastAutoId: -1,
};
}

if (this._storage.meta.formatVersion === 4) {
this._storage.meta.id = this.name;
this._storage.meta.formatVersion = 5;
}

if (this._storage.meta.formatVersion !== AlwatrStorageEngine.formatVersion) {
this._logger.error('load', 'storage_version_incompatible', {storageMeta: this._storage.meta});
throw new Error('storage_version_incompatible');
}

return storage;
this.save();
}

/**
Expand Down

0 comments on commit 10fc378

Please sign in to comment.