All files / src/core/strategies MemoryStrategy.ts

100% Statements 58/58
100% Branches 24/24
100% Functions 15/15
100% Lines 58/58

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 771x       1x 88x     88x 89x 89x   88x 43x 43x 88x 87x 87x   88x 67x 67x 88x 128x 128x   88x 16x 16x 88x 33x 33x   88x 2x 2x 88x 4x 4x   88x 17x 17x   88x 35x   35x 6x 6x 6x 13x 35x   88x 97x 97x   88x 7x   4x   4x   4x 4x 4x 4x 4x 7x   88x 87x 87x 88x  
import type { DataModel, StorageBase, ValueType } from "../types";
import { StorageEngine } from "../types";
 
/** @ignore */
export class MemoryStrategy implements StorageBase {
	private storage: Map<string, DataModel<ValueType>> = new Map();
 
	/** @internal */
	async init(): Promise<void> {
		return Promise.resolve();
	}
 
	set<T extends ValueType>(key: string, data: DataModel<T>): Promise<void> {
		return Promise.resolve(this.setSync(key, data));
	}
	setSync<T extends ValueType>(key: string, data: DataModel<T>): void {
		this.storage.set(key, data);
	}
 
	get<T extends ValueType>(key: string): Promise<DataModel<T> | undefined> {
		return Promise.resolve(this.getSync(key));
	}
	getSync<T extends ValueType>(key: string): DataModel<T> | undefined {
		return this.storage.get(key) as DataModel<T> | undefined;
	}
 
	getAll<T extends ValueType>(): Promise<Map<string, DataModel<T>> | null> {
		return Promise.resolve(this.getAllSync<T>());
	}
	getAllSync<T extends ValueType>(): Map<string, DataModel<T>> | null {
		return this.storage.size > 0 ? (this.storage as Map<string, DataModel<T>>) : null;
	}
 
	has(key: string): Promise<boolean> {
		return Promise.resolve(this.hasSync(key));
	}
	hasSync(key: string): boolean {
		return this.storage.has(key);
	}
 
	unset(key?: string): Promise<boolean> {
		return Promise.resolve(this.unsetSync(key));
	}
 
	unsetSync(key?: string): boolean {
		if (this.storage.size === 0) return false;
 
		if (!key) {
			this.storage.clear();
			return this.storage.size === 0;
		}
		return this.storage.delete(key);
	}
 
	get length(): number {
		return this.storage.size;
	}
 
	get bytes(): number {
		if (this.storage.size === 0) return 0;
 
		let totalBytes = 0;
 
		const entries = Array.from(this.storage.entries());
 
		entries.forEach(([key, value]) => {
			totalBytes += new TextEncoder().encode(key).length;
			totalBytes += new TextEncoder().encode(JSON.stringify(value)).length;
		});
		return totalBytes;
	}
 
	get type(): StorageEngine {
		return StorageEngine.Memory;
	}
}