diff --git a/core/storage-engine/package.json b/core/storage-engine/package.json index 3ab2be590..43c4909d2 100644 --- a/core/storage-engine/package.json +++ b/core/storage-engine/package.json @@ -37,6 +37,8 @@ }, "dependencies": { "@alwatr/logger": "^0.30.0", + "@alwatr/util": "^0.30.0", + "@alwatr/type": "^0.30.0", "exit-hook": "^3.2.0", "tslib": "^2.5.0" }, diff --git a/core/storage-engine/src/storage-engine.ts b/core/storage-engine/src/storage-engine.ts index 2d4d0bf90..f9739107a 100644 --- a/core/storage-engine/src/storage-engine.ts +++ b/core/storage-engine/src/storage-engine.ts @@ -1,9 +1,9 @@ import {resolve} from 'node:path'; import {createLogger, globalAlwatr, type AlwatrLogger} from '@alwatr/logger'; +import {readJsonFileSync, writeJsonFile, writeJsonFileSync} from '@alwatr/util/node'; import exitHook from 'exit-hook'; -import {readJsonFile, writeJsonFile} from './util.js'; import type {AlwatrStorageEngineConfig} from './type.js'; import type {AlwatrDocumentStorage, AlwatrDocumentObject} from '@alwatr/type'; @@ -146,13 +146,14 @@ export class AlwatrStorageEngine { this._logger.logMethodArgs?.('load', {name: this.name, path: this.storagePath}); - const storage = readJsonFile>(this.storagePath); + const storage = readJsonFileSync>(this.storagePath); if (storage === null) { this._logger.incident?.('load', 'file_not_found', 'Storage path not found, empty storage loaded', { @@ -353,30 +354,40 @@ export class AlwatrStorageEngine { this._logger.logMethodArgs?.('forceSave', {hasUnsavedChanges: this.hasUnsavedChanges}); if (this._saveTimer != null) { clearTimeout(this._saveTimer); this._saveTimer = null; } + return this._writeFile(); + } + + protected async _writeFile(): Promise { + if (this.hasUnsavedChanges) { + this.hasUnsavedChanges = false; + await writeJsonFile(this.storagePath, this._storage, this.saveBeautiful ? 2 : 0); + } + } + protected _writeFileSync(): void { if (this.hasUnsavedChanges) { - writeJsonFile(this.storagePath, this._storage, this.saveBeautiful ? 2 : 0); this.hasUnsavedChanges = false; + writeJsonFileSync(this.storagePath, this._storage, this.saveBeautiful ? 2 : 0); } } diff --git a/core/storage-engine/src/util.ts b/core/storage-engine/src/util.ts deleted file mode 100644 index 2e7f4a6b1..000000000 --- a/core/storage-engine/src/util.ts +++ /dev/null @@ -1,83 +0,0 @@ -import {existsSync, mkdirSync, writeFileSync, renameSync, readFileSync} from 'node:fs'; -import {dirname} from 'node:path'; - -// TODO: add debug log - -/** - * Enhanced read json file. - * @example - * const fileContent = readJsonFile('./file.json'); - */ -export function readJsonFile(path: string): T | null { - if (!existsSync(path)) { - return null; - } - - const timeKey = path.substring(path.lastIndexOf('/') + 1); - - let fileContent: string; - try { - console.time('AlwatrStorageEngine Read ' + timeKey); - fileContent = readFileSync(path, {encoding: 'utf-8'}); - console.timeEnd('AlwatrStorageEngine Read ' + timeKey); - } - catch (err) { - throw new Error('read_file_failed'); - } - - try { - console.time('AlwatrStorageEngine Parse ' + timeKey); - const data = JSON.parse(fileContent) as T; - console.timeEnd('AlwatrStorageEngine Parse ' + timeKey); - return data; - } - catch (err) { - throw new Error('invalid_json'); - } -} - -/** - * Enhanced write json file. - * @example - * writeJsonFile('./file.json', { a:1, b:2, c:3 }); - */ -export function writeJsonFile(path: string, data: unknown, space?: string | number | undefined): void { - const timeKey = path.substring(path.lastIndexOf('/') + 1); - - let jsonContent; - try { - console.time('AlwatrStorageEngine Stringify ' + timeKey); - jsonContent = JSON.stringify(data, null, space); - console.timeEnd('AlwatrStorageEngine Stringify ' + timeKey); - } - catch (err) { - throw new Error('stringify_failed'); - } - - if (existsSync(path)) { - try { - renameSync(path, path + '.bk'); - } - catch (err) { - // @TODO: handle in forceSave and log with logger - console.error('cannot rename file!'); - } - } - else { - try { - mkdirSync(dirname(path), {recursive: true}); - } - catch (err) { - throw new Error('make_dir_failed'); - } - } - - try { - console.time('AlwatrStorageEngine Write ' + timeKey); - writeFileSync(path, jsonContent, {encoding: 'utf-8', flag: 'w'}); - console.timeEnd('AlwatrStorageEngine Write ' + timeKey); - } - catch (err) { - throw new Error('write_file_failed'); - } -} diff --git a/core/storage-engine/tsconfig.json b/core/storage-engine/tsconfig.json index 5689e0024..8b72465a6 100644 --- a/core/storage-engine/tsconfig.json +++ b/core/storage-engine/tsconfig.json @@ -11,6 +11,7 @@ "exclude": [], "references": [ {"path": "../logger"}, + {"path": "../util"}, {"path": "../type"} ] }