All files / src/models TransactionModel.ts

89.83% Statements 53/59
62.5% Branches 40/64
84.61% Functions 11/13
89.83% Lines 53/59

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 2531x   1x                                                   1x                         11x 11x                             28x             2x                                   11x   11x         11x   11x 7x   4x                             2x   2x 2x 1x   1x                                   3x         3x 3x         3x   3x                 3x 3x           3x     3x       3x               11x 4x   4x   7x                   3x 1x   1x   2x   2x                     3x 1x   1x 2x         2x 2x                   2x 2x   2x 4x   2x     2x     2x 2x       2x 1x        
import { isIPrimitive } from 'src/interfaces/DataType/IPrimitive';
import { ILogger, ILogger_ } from 'src/interfaces/ILogger';
import { DIContainer } from 'src/libs/DependencyInjection/DIContainer';
import { IDIContainer } from 'src/libs/DependencyInjection/interfaces/IDIContainer';
 
/**
 * The type of return value of the `callWriteChanges` method.
 */
type WriteChangesReturnType = {
    /**
     * A promise that resolves when the changes are written to the file.
     */
    promise: Promise<void> | undefined;
    /**
     * A boolean that indicates whether the writeChanges function was called.
     */
    writeTriggered: boolean;
};
 
/**
 * A class that handles transactions.
 * @remarks - A transaction is a set of changes that are applied to the model at once.
 * - This is useful when multiple changes need to be applied to the model, but the changes should only be written to the file once all changes have been applied.
 * - This is also useful when the changes should be applied to the model, but not written to the file yet.
 * @summary - To start a transaction, call the `startTransaction` method.
 * - To apply the changes to the model, call the `finishTransaction` method.
 * - To discard the changes, call the `abortTransaction` method.
 */
export class TransactionModel<T> {
    protected _dependencies: IDIContainer;
    protected _logger?: ILogger;
    /**
     * A promise that resolves when the changes are written to the file.
     */
    private _writeChangesPromise: Promise<void> | undefined;
    /**
     * Returns the promise that resolves when the last changes are written to the file.
     */
    protected get writeChangesPromise(): Promise<void> | undefined {
        return this._writeChangesPromise;
    }
    private _isTransactionActive = false;
    protected _changes: Partial<T> = {};
    /**
     * A function that writes the changes to the file.
     * @remarks - This function is called when the transaction is finished or without a active transaction immediately.
     * @param update The changes to write.
     * @param previousPromise A promise that resolves when the previous changes are written to the file.
     */
    protected _writeChanges:
        | ((update: T, previousPromise?: Promise<void>) => Promise<void>)
        | undefined;
 
    /**
     * Returns whether a transaction is active.
     */
    public get isTransactionActive(): boolean {
        return this._isTransactionActive;
    }
 
    /**
     * Returns whether changes exist.
     */
    private get changesExisting(): boolean {
        return !(
            Object.keys(this._changes).length === 0 &&
            this._changes.constructor === Object
        );
    }
 
    /**
     * Creates a new instance of the TransactionModel class.
     * @param writeChanges A function that writes the changes to the file.
     * @param dependencies The optional dependencies to use.
     * @remarks - If no `writeChanges` function is provided, a transaction is started immediately.
     */
    constructor(
        writeChanges:
            | ((update: T, previousPromise?: Promise<void>) => Promise<void>)
            | undefined,
        dependencies?: IDIContainer,
    ) {
        this._dependencies = dependencies ?? DIContainer.getInstance();
 
        this._logger = this._dependencies
            .resolve<ILogger_>('ILogger_', false)
            ?.getLogger('Model');
 
        // Bind the updateKeyValue method to the instance; its required for the ProxyHandler Delegate.
        this.updateKeyValue = this.updateKeyValue.bind(this);
 
        if (writeChanges) {
            this._writeChanges = writeChanges;
        } else {
            this.startTransaction();
        }
    }
 
    /**
     * Sets the callback function for writing changes to the transaction model.
     * @param writeChanges The callback function that takes an update of type T and returns a Promise that resolves when the changes are written.
     * @remarks - If a transaction is active, and changes exist, the transaction is finished, else it is aborted.
     */
    public setWriteChanges(
        writeChanges: (
            update: T,
            previousPromise?: Promise<void>,
        ) => Promise<void>,
    ): void {
        this._writeChanges = writeChanges;
 
        if (this.isTransactionActive) {
            if (this.changesExisting) {
                this.finishTransaction();
            } else {
                this.abortTransaction();
            }
        }
    }
 
    /**
     * Calls the `writeChanges` function if it is available.
     * @param update The changes to write. Defaults to `this.changes` if not provided.
     * @returns An object with a promise that resolves when the changes are written to the file and a boolean that indicates whether the writeChanges function was called.
     * @remarks - If the `writeChanges` function is available, it will be called asynchronously (No waiting for the function to finish).
     * - If the `writeChanges` function is not available, this method does nothing.
     * @remarks - If the `writeChanges` function is called, the `changes` property is set to an empty object after the function is called
     * and the `_writeChangesPromise` property is set to the promise that resolves when the changes are written to the file.
     * - If the `writeChanges` function is not called, the `changes` property is not changed and the `_writeChangesPromise` property is set to itself or `undefined`.
     */
    private callWriteChanges(
        update: T = this._changes as T,
    ): WriteChangesReturnType {
        const writeChanges: WriteChangesReturnType = {
            promise: undefined,
            writeTriggered: false,
        };
 
        if (this._writeChanges) {
            const promise = this._writeChanges(
                update,
                this._writeChangesPromise,
            );
 
            promise
                .then(() => {
                    this._logger?.debug('Changes written to file');
                })
                .catch((error) => {
                    this._logger?.error(
                        'Failed to write changes to file:',
                        error,
                    );
                });
 
            writeChanges.promise = promise;
            writeChanges.writeTriggered = true;
        } else E{
            this._logger?.debug('No `writeChanges` function available');
        }
 
        // Reset changes if writeChanges was called
        this._changes = writeChanges.writeTriggered ? {} : this._changes;
 
        // Set the promise if writeChanges was called and the promise is available.
        this._writeChangesPromise = writeChanges.promise
            ? writeChanges.promise
            : undefined;
 
        return writeChanges;
    }
 
    /**
     * Starts a transaction
     * @remarks - If a transaction is already active, this method does nothing and logs a warning.
     */
    public startTransaction(): void {
        if (this.isTransactionActive) {
            this._logger?.warn('Transaction already active');
 
            return;
        }
        this._isTransactionActive = true;
    }
 
    /**
     * Finishes a transaction
     * @remarks - If no transaction is active, this method does nothing and logs a warning.
     * - This method writes the changes to the file.
     * @remarks - If the `writeChanges` method is not available, this method does nothing. The available changes are not discarded!
     */
    public finishTransaction(): void {
        if (!this.isTransactionActive) {
            this._logger?.warn('No transaction active');
 
            return;
        }
        const writeChanges = this.callWriteChanges();
 
        this._isTransactionActive = writeChanges.writeTriggered
            ? false
            : this._isTransactionActive;
    }
 
    /**
     * Aborts a transaction and discards all changes.
     * @remarks - If no transaction is active, this method does nothing and logs a warning.
     * - This method discards all changes!
     */
    public abortTransaction(): void {
        if (!this.isTransactionActive) {
            this._logger?.warn('No transaction active');
 
            return;
        } else Iif (!this._writeChanges) {
            this._logger?.warn('No `writeChanges` function available');
 
            return;
        }
        this._changes = {};
        this._isTransactionActive = false;
    }
 
    /**
     * Updates the value of the given key.
     * @param key The key to update as path with dots as separator. Example: `data.title`.
     * @param value The value to set.
     * @remarks If no transaction is active, the changes are written to the file immediately!
     */
    protected updateKeyValue(key: string, value: unknown): void {
        const keys = key.split('.');
        let current = this._changes as Record<string, unknown>;
 
        keys.forEach((k, index) => {
            if (index === keys.length - 1) {
                // Check if the value is a custom complex data type and get the frontmatter object if it is
                Iif (isIPrimitive(value)) {
                    current[k] = value.primitiveOf();
                } else {
                    current[k] = value;
                }
            } else {
                current[k] = current[k] || {};
                current = current[k] as Record<string, unknown>;
            }
        });
 
        if (!this.isTransactionActive) {
            this.callWriteChanges();
        }
    }
}
 
Zur TypeDoc-Dokumentation