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 | 1x 1x 1x 1x 45x 45x 45x 45x 45x 476x 476x 476x 45x 389x 389x 389x 389x 389x 45x 38x 38x 38x 38x 7x 7x 6x 6x 1x 1x 7x 38x 45x 105x 105x 105x 105x 8x 8x 7x 7x 1x 1x 8x 105x 45x 30x 30x 30x 30x 3x 3x 2x 2x 1x 1x 3x 30x 45x 57x 57x 57x 57x 2x 2x 1x 1x 1x 1x 2x 57x 45x 38x 37x 37x 38x 38x 38x 45x 105x 105x 105x 105x 105x 45x 30x 30x 30x 30x 30x 16x 30x 13x 13x 30x 45x 57x 57x 57x 57x 57x 17x 57x 39x 39x 57x 45x | /**
* @module JsonFileHelper
* @description This module provides a helper class for managing JSON files in a key-value store.
* It includes methods for loading, saving, and ensuring the existence of JSON files and directories.
* It is designed to work with a customizable directory and file name for storing key-value pairs.
* @author Heliomar Marques
*/
import fs from "node:fs";
import path from "node:path";
import writeFileAtomic from "write-file-atomic";
import type { Options, valueTypes } from "./types";
export const DEFAULT_DIR_NAME = "localdb";
export const DEFAULT_FILE_NAME = "keyvalues.json";
export class JsonFileHelper {
/**
* The options for the JsonFileHelper.
* @type {@link Options}
* @private
*/
options: Options;
/**
* Creates an instance of JsonFileHelper.
*
* @param {@link Options} options - The options for the JsonFileHelper.
* @constructor
*/
constructor(options: Options) {
this.options = options;
}
/**
* Returns the path to the keyvalues directory. The path
* may be customized by the developer by using
* `configure()`.
*
* @returns The path to the keyvalues directory.
* @internal
*/
private getJsonDirPath(): string {
const dir = (this.options.dir ?? path.resolve(DEFAULT_DIR_NAME)).trim();
return dir === "" ? "./" : dir;
}
/**
* Returns the path to the keyvalues file. The file name
* may be customized by the developer using `configure()`.
*
* @returns The path to the keyvalues file.
* @internal
*/
public getJsonFilePath(): string {
const dir = this.getJsonDirPath();
let fileName = this.options.fileName.trim();
fileName = fileName === "" ? DEFAULT_FILE_NAME : fileName;
return path.join(dir, fileName);
}
/**
* Ensures that the keyvalues file exists. If it does not
* exist, then it is created.
*
* @returns A promise which resolves when the keyvalues file exists.
* @internal
*/
private async ensureJsonFile(): Promise<void> {
const filePath = this.getJsonFilePath();
try {
await fs.promises.stat(filePath);
} catch (error) {
const ex = error as NodeJS.ErrnoException;
if (ex?.code === "ENOENT") {
await this.saveKeyValues({});
} else {
throw error;
}
}
}
/**
* Ensures that the keyvalues file exists. If it does not
* exist, then it is created.
*
* @internal
*/
private ensureJsonFileSync(): void {
const filePath = this.getJsonFilePath();
try {
fs.statSync(filePath);
} catch (error) {
const ex = error as NodeJS.ErrnoException;
if (ex?.code === "ENOENT") {
this.saveKeyValuesSync({});
} else {
throw error;
}
}
}
/**
* Ensures that the KeyValues directory exists. If it does
* not exist, then it is created.
*
* @returns A promise which resolves when the keyvalues dir exists.
* @internal
*/
private async ensureJsonDir(): Promise<void> {
const dirPath = this.getJsonDirPath();
try {
await fs.promises.stat(dirPath);
} catch (error) {
const ex = error as NodeJS.ErrnoException;
if (ex?.code === "ENOENT") {
await fs.promises.mkdir(dirPath, { recursive: true });
} else {
throw error;
}
}
}
/**
* Ensures that the KeyValues directory exists synchronously. If it does not exist,
* then it is created.
*
* @returns {void}
* @internal
*/
private ensureJsonDirSync(): void {
const dirPath = this.getJsonDirPath();
try {
fs.statSync(dirPath);
} catch (error) {
const ex = error as NodeJS.ErrnoException;
if (ex?.code === "ENOENT") {
fs.mkdirSync(dirPath, { recursive: true });
} else {
throw error;
}
}
}
/**
* Asynchronously loads key-value pairs from a JSON file. First ensures that the file exists,
* then reads the file and parses its contents into a JavaScript object.
*
* @template T - The type of the key-value pairs.
* @return {Promise<T>} A promise that resolves with the key-value pairs.
* @internal
*/
public async loadKeyValues<T extends valueTypes>(): Promise<T> {
await this.ensureJsonFile();
const filePath = this.getJsonFilePath();
const data = await fs.promises.readFile(filePath, "utf-8");
// fs.promises.readFile com 'utf-8' sempre retorna uma string, então a verificação de array é desnecessária.
const jsonData = data || "{}";
return JSON.parse(jsonData) as T;
}
/**
* Loads the key-value pairs synchronously from the JSON file.
*
* @template T - The type of the key-value pairs.
* @returns {T} - The loaded key-value pairs.
* @internal
*/
public loadKeyValuesSync<T extends valueTypes>(): T {
this.ensureJsonFileSync();
const filePath = this.getJsonFilePath();
const data = fs.readFileSync(filePath, "utf-8");
return JSON.parse(data.length ? data : "{}") as T;
}
/**
* Saves the keyvalues to the disk.
*
* @param {T} obj - The keyvalues object to save.
* @return {Promise<void>} A promise that resolves when the keyvalues have been saved.
* @internal
*/
public async saveKeyValues<T>(obj: T): Promise<void> {
const filePath = this.getJsonFilePath();
const numSpaces = this.options.prettify ? this.options.numSpaces : 0;
const content = JSON.stringify(obj, null, numSpaces);
await this.ensureJsonDir();
if (this.options.atomicSave) {
await writeFileAtomic(filePath, content);
} else {
await fs.promises.writeFile(filePath, content);
}
}
/**
* Saves the keyvalues to the disk synchronously.
*
* @param {T} obj - The keyvalues object to save.
* @return {void} This function does not return anything.
* @internal
*/
public saveKeyValuesSync<T>(obj: T): void {
const filePath = this.getJsonFilePath();
const numSpaces = this.options.prettify ? this.options.numSpaces : 0;
const data = JSON.stringify(obj, null, numSpaces);
this.ensureJsonDirSync();
if (this.options.atomicSave) {
writeFileAtomic.sync(filePath, data);
} else {
fs.writeFileSync(filePath, data);
}
}
}
|