outers
Version:
outers - a all in one package for your day to day use
334 lines • 19.6 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _CreateNewShortStorage_StorageName, _CreateNewShortStorage_StoragePath, _CreateNewShortStorage_MaxStorageSize, _CreateNewShortStorage_EncryptionKey, _CreateNewShortStorage_StorageFullPATH;
Object.defineProperty(exports, "__esModule", { value: true });
/* eslint-disable @typescript-eslint/no-explicit-any */
const promises_1 = require("node:fs/promises"); // Import Node.js Dependencies
// Import Encryption and Decryption Functions
const Dispatcher_1 = __importDefault(require("../Encryption - Decryption/Dispatcher")); // Import Encryption and Decryption Functions
// Main Function Sto Store Data in Short Storage
/**
* Represents a short storage for saving and retrieving data.
*/
class CreateNewShortStorage {
/**
* Constructs a new instance of the ShortStorage class.
* @param {string} [StorageName] - The name of the storage. Defaults to "outers" if not provided.
* @param {number} [MaxStorageSize] - The maximum size of the storage in Megabytes. Defaults to 1MB if not provided.
* @param {string} [EncryptionKey] - The encryption key for the storage. If not provided, a default encryption key will be generated based on the storage name, storage path, and the current version of Node.js.
* @param {string} [StoragePath] - The path where the storage is located. Defaults to "Cache/" if not provided.
*/
constructor(StorageName, MaxStorageSize, EncryptionKey, StoragePath) {
var _a;
// Properties
_CreateNewShortStorage_StorageName.set(this, void 0); // Storage Name (Private)
_CreateNewShortStorage_StoragePath.set(this, void 0); // Storage Path (Private)
_CreateNewShortStorage_MaxStorageSize.set(this, void 0); // Max Storage Size (Private)
_CreateNewShortStorage_EncryptionKey.set(this, void 0); // Encryption Key (Private)
_CreateNewShortStorage_StorageFullPATH.set(this, void 0); // Storage Full PATH (Public)
__classPrivateFieldSet(this, _CreateNewShortStorage_StorageName, (_a = StorageName === null || StorageName === void 0 ? void 0 : StorageName.toLowerCase()) !== null && _a !== void 0 ? _a : "outers", "f"); // Set Storage Name
__classPrivateFieldSet(this, _CreateNewShortStorage_StoragePath, StoragePath !== null && StoragePath !== void 0 ? StoragePath : ".Cache/", "f"); // Set Storage Path
__classPrivateFieldSet(this, _CreateNewShortStorage_MaxStorageSize, MaxStorageSize !== null && MaxStorageSize !== void 0 ? MaxStorageSize : 1, "f"); // Set Max Storage Size to 1MB
__classPrivateFieldSet(this, _CreateNewShortStorage_StorageFullPATH, `${__classPrivateFieldGet(this, _CreateNewShortStorage_StoragePath, "f")}.${__classPrivateFieldGet(this, _CreateNewShortStorage_StorageName, "f")}.storage.json`, "f"); // Set Storage Full PATH
this.createShortStorage(); // Create Short Storage
__classPrivateFieldSet(this, _CreateNewShortStorage_EncryptionKey, EncryptionKey !== null && EncryptionKey !== void 0 ? EncryptionKey : `${__classPrivateFieldGet(this, _CreateNewShortStorage_StorageName, "f")
.split("")
.reverse()
.join("")
.toUpperCase()}-${__classPrivateFieldGet(this, _CreateNewShortStorage_StoragePath, "f")
.split("")
.reverse()
.join("")
.toUpperCase()}-${process.versions.node
.trim()
.split("")
.reverse()
.join("")}`, "f"); // Create Encryption Key if it is not Provided or Use Provided Encryption Key
}
/**
* Saves the provided data with the given title to the storage.
* @param {string} Title - The title of the data.
* @param {any} Data - The data to be saved.
* @returns {Promise<ShortStorage>} - A promise that resolves when the data is successfully saved.
*/
Save(Title, Data) {
return __awaiter(this, void 0, void 0, function* () {
// Check if File size is bigger than Max Storage Size
const FileStats = yield (0, promises_1.stat)(__classPrivateFieldGet(this, _CreateNewShortStorage_StorageFullPATH, "f")); // Get File Stats
// Convert File Size to Megabytes and Check if it's bigger than Max Storage Size
const fileSizeInMegabytes = FileStats.size / (1024 * 1024); // Convert File Size to Megabytes from bytes
if (fileSizeInMegabytes >= __classPrivateFieldGet(this, _CreateNewShortStorage_MaxStorageSize, "f")) {
// Check if File Size is Reached to Max Storage Size
return {
status: 400,
message: "Storage is full, please use another instance or increase the storage size.",
Data: [],
TotalData: 0,
};
}
// Check if Data is Already Exists in Short Storage
const FindData = yield this.Get(Title); // Get Data
if (FindData.Data.length !== 0) {
return {
status: 403,
message: "Data Already Exists",
Data: FindData.Data,
TotalData: FindData.TotalData,
};
}
const RawData = yield (0, promises_1.readFile)(__classPrivateFieldGet(this, _CreateNewShortStorage_StorageFullPATH, "f"), "utf-8"); // Get Raw Data
const ParsedData = JSON.parse(RawData); // Parsed The Data
// Encrypt Data if Encryption Key is Provided
const UserProvidedData = yield new Dispatcher_1.default(String(__classPrivateFieldGet(this, _CreateNewShortStorage_EncryptionKey, "f"))).Encrypt(Data); // Set User Provided Data
const UserProvidedTitle = yield new Dispatcher_1.default(String(__classPrivateFieldGet(this, _CreateNewShortStorage_EncryptionKey, "f"))).Encrypt(Title); // Set User Provided Title
// Push The New Data In The Array
ParsedData.push({
Title: UserProvidedTitle,
Data: UserProvidedData,
});
// Write The New Data in File
yield (0, promises_1.writeFile)(__classPrivateFieldGet(this, _CreateNewShortStorage_StorageFullPATH, "f"), JSON.stringify(ParsedData), "utf-8"); // Write Data in File
return {
status: 200,
message: "Data Saved Successfully",
Data: [
{
Title,
Data,
},
],
TotalData: 1,
};
});
}
/**
* Retrieves data from the storage based on the provided title.
* @param Title - The title of the data to retrieve.
* @returns A promise that resolves to an object containing the status, message, and retrieved data.
*/
Get(Title) {
return __awaiter(this, void 0, void 0, function* () {
const RawData = yield (0, promises_1.readFile)(__classPrivateFieldGet(this, _CreateNewShortStorage_StorageFullPATH, "f"), "utf-8"); // Get Raw Data
const ParsedData = JSON.parse(RawData); // Parsed The Data
// Find The Data with Decryption if Encryption Key is Provided
const EncryptedData = yield Promise.all(ParsedData.map((Data) => __awaiter(this, void 0, void 0, function* () {
const DecryptedTitle = JSON.parse(yield new Dispatcher_1.default(String(__classPrivateFieldGet(this, _CreateNewShortStorage_EncryptionKey, "f"))).Decrypt(Data.Title)); // Decrypt Title if Encryption Key is Provided
const DecryptedData = JSON.parse(yield new Dispatcher_1.default(String(__classPrivateFieldGet(this, _CreateNewShortStorage_EncryptionKey, "f"))).Decrypt(Data.Data)); // Decrypt Data if Encryption Key is Provided
// Check if Title is Provided and Match with Decrypted Title
if (Title === undefined || DecryptedTitle === Title) {
return {
Title: DecryptedTitle,
Data: DecryptedData,
};
}
else {
return null; // Do not include in the final result
}
})));
// Filter out null values (where Title did not match)
const EncryptedFilteredData = EncryptedData.filter(Boolean); // Filter out null values (where Title did not match)
if (EncryptedFilteredData.length === 0) {
const PreparedDataForError = {
status: 404,
message: "Data Not Found",
Data: [],
TotalData: 0,
};
return PreparedDataForError;
}
return {
status: 200,
message: "Data Found Successfully",
Data: EncryptedFilteredData,
TotalData: EncryptedFilteredData.length,
}; // Return Data;
});
}
// Update Data in Short Storage
/**
* Updates the data in the Short Storage with the specified title.
* If the data is not found, returns a 404 status with a "Data Not Found" message.
* Otherwise, deletes the old data, adds the new data, and writes the updated data to the storage file.
* Returns a 200 status with a "Data Updated Successfully" message and the updated data.
* @param {string} Title - The title of the data to be updated.
* @param {any} NewData - The new data to be added.
* @returns {Promise<{ status: number, message: string, Data?: { Title: string, Data: any } }>} - The status, message, and updated data (if successful).
*/
Update(Title, NewData) {
return __awaiter(this, void 0, void 0, function* () {
// Check if Data is Already Exists in Short Storage
if ((yield this.Get(Title)).Data.length === 0) {
return {
status: 404,
message: "Data Not Found",
Data: [],
TotalData: 0,
};
}
// Delete The Old Data
const AllFindData = yield this.Get(); // Get All Data in Storage File
// Delete The Data
const RemovedData = AllFindData.Data.filter((Data) => Data.Title !== Title);
// Push The New Data In The Array
RemovedData.push({
Title: Title,
Data: NewData,
}); // Push The New Data In The Array
// Filter out null values (where Title did not match)
const EncryptedBuiltData = yield this.CreateEncryptedData(RemovedData); // Filter out null values (where Title did not match)
// Unlock File Before Write Data
// Write The New Data in File
yield (0, promises_1.writeFile)(__classPrivateFieldGet(this, _CreateNewShortStorage_StorageFullPATH, "f"), JSON.stringify(EncryptedBuiltData), "utf-8"); // Write Data in File
// Lock File After Write Data
return {
status: 200,
message: "Data Updated Successfully",
Data: [
{
Title,
Data: NewData,
},
],
TotalData: 1,
};
});
}
// Delete Data From Short Storage
/**
* Deletes a data entry from the storage based on the provided title.
* @param {string} Title - The title of the data entry to be deleted.
* @returns {Promise<ShortStorage>} A promise that resolves to the deleted data entry or an error object.
*/
Delete(Title) {
return __awaiter(this, void 0, void 0, function* () {
// Get All Data in Storage File Before Delete
const ParsedData = (yield this.Get()).Data; // Parsed The Data
// Find The Data
const Data = ParsedData.filter((Data) => Data.Title === Title);
if (!Data) {
return {
status: 404,
message: "Data Not Found",
Data: [],
TotalData: 0,
};
}
// Delete The Data
const NewData = ParsedData.filter((Data) => Data.Title !== Title);
// Filter out null values (where Title did not match)
const EncryptedBuiltData = yield this.CreateEncryptedData(NewData); // Filter out null values (where Title did not match)
// Unlock File Before Write Data
// Write The New Data in File
yield (0, promises_1.writeFile)(__classPrivateFieldGet(this, _CreateNewShortStorage_StorageFullPATH, "f"), JSON.stringify(EncryptedBuiltData), "utf-8"); // Write Data in File
// Lock File After Write Data
return {
status: 200,
message: "Data Deleted Successfully",
Data,
TotalData: Data.length,
};
});
}
// A Public Method to Delete Data Storage File
/**
* Deletes the storage directory and file.
*
* @returns A promise that resolves to a ShortStorage object with the status and message.
* If the storage is deleted successfully, the object will also contain the data and total data count.
* If the storage is not found, the object will have a status of 404 and a corresponding error message.
*/
DeleteStorage() {
return __awaiter(this, void 0, void 0, function* () {
// Check if the directory exists, and create it if not
try {
yield (0, promises_1.access)(__classPrivateFieldGet(this, _CreateNewShortStorage_StoragePath, "f")); // Check if Directory Exists
// Get All Data in Storage File Before Delete
const AllDataInStorage = yield this.Get(); // Get All Data in Storage File
// Unlock File Before Delete Data
// Delete All Data in Storage File
yield (0, promises_1.unlink)(__classPrivateFieldGet(this, _CreateNewShortStorage_StorageFullPATH, "f")); // Delete File
yield (0, promises_1.rmdir)(`${__classPrivateFieldGet(this, _CreateNewShortStorage_StoragePath, "f")}`); // Delete Storage Directory
return {
status: 200,
message: "Storage Deleted Successfully",
Data: AllDataInStorage.Data,
TotalData: AllDataInStorage.TotalData,
};
}
catch (error) {
return {
status: 404,
message: "Storage Not Found in Management PATH",
Data: [],
TotalData: 0,
};
}
});
}
// A Private Method for Create Short Storage Folder
/**
* Creates a short storage by checking if the directory exists and creating it if not.
* Then, it creates a short storage file with an empty JSON object.
*/
createShortStorage() {
return __awaiter(this, void 0, void 0, function* () {
// Check if the directory exists, and create it if not
try {
yield (0, promises_1.access)(__classPrivateFieldGet(this, _CreateNewShortStorage_StorageFullPATH, "f")); // Check if Directory Exists
}
catch (error) {
// Directory does not exist, create it
yield (0, promises_1.mkdir)(`${__classPrivateFieldGet(this, _CreateNewShortStorage_StoragePath, "f")}`, { recursive: true }); // Create Directory
// Write Empty Data in this File
yield (0, promises_1.writeFile)(__classPrivateFieldGet(this, _CreateNewShortStorage_StorageFullPATH, "f"), JSON.stringify([]), "utf-8"); // Create Storage File
}
});
}
/**
* Encrypts the provided data using the encryption key.
* @param UnEncryptedData - The data to be encrypted.
* @returns The encrypted data.
*/
CreateEncryptedData(UnEncryptedData) {
return __awaiter(this, void 0, void 0, function* () {
// Encrypt Data if Encryption Key is Provided
const EncryptedData = yield Promise.all(UnEncryptedData.map((Data) => __awaiter(this, void 0, void 0, function* () {
const EncryptedTitle = yield new Dispatcher_1.default(String(__classPrivateFieldGet(this, _CreateNewShortStorage_EncryptionKey, "f"))).Encrypt(Data.Title);
// Encrypt Title if Encryption Key is Provided
const EncryptedData = yield new Dispatcher_1.default(String(__classPrivateFieldGet(this, _CreateNewShortStorage_EncryptionKey, "f"))).Encrypt(Data.Data); // Encrypt Data if Encryption Key is Provided
// Check if Title is Provided and Match with Decrypted Title
return {
Title: EncryptedTitle,
Data: EncryptedData,
};
})));
// Filter out null values (where Title did not match)
return EncryptedData.filter(Boolean); // Filter out null values (where Title did not match)
});
}
}
_CreateNewShortStorage_StorageName = new WeakMap(), _CreateNewShortStorage_StoragePath = new WeakMap(), _CreateNewShortStorage_MaxStorageSize = new WeakMap(), _CreateNewShortStorage_EncryptionKey = new WeakMap(), _CreateNewShortStorage_StorageFullPATH = new WeakMap();
exports.default = CreateNewShortStorage;
//# sourceMappingURL=ShortStorage.storage.js.map