axiodb
Version:
A blazing-fast, lightweight, and scalable nodejs package based DBMS for modern application. Supports schemas, encryption, and advanced query capabilities.
208 lines • 10 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 __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const response_helper_1 = __importDefault(require("../../Helper/response.helper"));
// Operations
const Create_operation_1 = __importDefault(require("../CRUD Operation/Create.operation"));
const Reader_operation_1 = __importDefault(require("../CRUD Operation/Reader.operation"));
const Delete_operation_1 = __importDefault(require("../CRUD Operation/Delete.operation"));
const Update_operation_1 = __importDefault(require("../CRUD Operation/Update.operation"));
const Aggregation_Operation_1 = __importDefault(require("../Aggregation/Aggregation.Operation"));
const outers_1 = require("outers");
// Validator
const validator_models_1 = __importDefault(require("../../Schema/validator.models"));
// Converter
const Converter_helper_1 = __importDefault(require("../../Helper/Converter.helper"));
const DataTypes_models_1 = require("../../Schema/DataTypes.models");
const FolderManager_1 = __importDefault(require("../../engine/Filesystem/FolderManager"));
/**
* Represents a collection inside a database.
*/
class Collection {
constructor(name, path, isSchemaNeeded, schema, isEncrypted = false, cryptoInstance, encryptionKey) {
this.name = name;
this.path = path;
if (isSchemaNeeded == true && !schema) {
throw new Error("Schema is required when isSchemaNeeded is true");
}
else {
this.isSchemaNeeded = isSchemaNeeded;
this.schema = schema;
}
this.isEncrypted = isEncrypted;
this.cryptoInstance = cryptoInstance;
this.Converter = new Converter_helper_1.default();
this.updatedAt = new Date().toISOString();
this.encryptionKey = encryptionKey;
// Initialize the Insertion class
this.Insertion = new Create_operation_1.default(this.name, this.path);
}
/**
* Get Numbers of Documents in the Collection
* @returns {Promise<number>} - A promise that resolves with the number of documents in the collection.
* @throws {Error} - Throws an error if the collection is empty or if there is an issue with the query.
*/
totalDocuments() {
return __awaiter(this, void 0, void 0, function* () {
// Check if the collection is empty
if (!this.name) {
throw new Error("Collection name cannot be empty");
}
// Check if the path is empty
if (!this.path) {
throw new Error("Path cannot be empty");
}
try {
// Check if Directory Locked or not
const isLocked = yield new FolderManager_1.default().IsDirectoryLocked(this.path);
if ("data" in isLocked) {
if (isLocked.data === false) {
// List all files in the directory
const files = yield new FolderManager_1.default().ListDirectory(this.path);
return new response_helper_1.default().Success({
message: "Total Documents in the Collection",
total: files.data.length,
});
}
else {
// if Directory is locked then unlock it
const unlockResponse = yield new FolderManager_1.default().UnlockDirectory(this.path);
if ("data" in unlockResponse) {
// List all files in the directory
const files = yield new FolderManager_1.default().ListDirectory(this.path);
// Lock the directory again
const lockResponse = yield new FolderManager_1.default().LockDirectory(this.path);
if ("data" in lockResponse) {
return new response_helper_1.default().Success({
message: "Total Documents in the Collection",
total: files.data.length,
});
}
else {
return new response_helper_1.default().Error("Cannot lock the directory");
}
}
else {
return new response_helper_1.default().Error("Cannot unlock the directory");
}
}
}
else {
return new response_helper_1.default().Error("Cannot access the directory");
}
}
catch (error) {
return new response_helper_1.default().Error(error);
}
});
}
/**
* Inserts a document into the collection.
* @param {object} data - The data to be inserted.
* @returns {Promise<any>} - A promise that resolves with the response of the insertion operation.
*/
insert(data) {
return __awaiter(this, void 0, void 0, function* () {
// Check if data is empty or not
if (!data) {
throw new Error("Data cannot be empty");
}
// Check if data is an object or not
if (typeof data !== "object") {
throw new Error("Data must be an object.");
}
// Add the documentId to the data
const documentId = yield this.Insertion.generateUniqueDocumentId();
data.documentId = documentId;
// Insert the updatedAt field in schema & data
data.updatedAt = this.updatedAt;
if (this.isSchemaNeeded == true) {
this.schema.updatedAt = DataTypes_models_1.SchemaTypes.date().required();
this.schema.documentId = DataTypes_models_1.SchemaTypes.string().required();
// Validate the data
const validator = yield (0, validator_models_1.default)(this.schema, data, false);
if (validator === null || validator === void 0 ? void 0 : validator.details) {
outers_1.Console.red("Validation Error", validator.details);
return new response_helper_1.default().Error(validator.details);
}
}
// Encrypt the data if crypto is enabled
if (this.cryptoInstance && this.isEncrypted) {
data = yield this.cryptoInstance.encrypt(this.Converter.ToString(data));
}
// Save the data
return yield this.Insertion.Save(data, documentId);
});
}
/**
* Reads a document from the collection.
* @param {object} query - The query to be executed
* @returns {Reader} - An instance of the Reader class.
*/
query(query) {
// Check if documentId is empty or not
if (!query) {
throw new Error("Query cannot be empty");
}
// Read the data
return new Reader_operation_1.default(this.name, this.path, query, this.isEncrypted, this.encryptionKey);
}
/**
* Initiates an aggregation operation on the collection with the provided pipeline steps.
* @param {object[]} PipelineQuerySteps - The pipeline steps to be executed.
* @returns {Aggregation} - An instance of the Aggregation class.
* @throws {Error} Throws an error if the pipeline steps are empty.
* @example
* ```typescript
* // Aggregate the collection to get the total count of documents
* collection.aggregate([{$match: {}}, ${group: {_id: null, count: {$sum: 1}}}]).exec();
* ```
*/
aggregate(PipelineQuerySteps) {
// Check if Pipeline Steps is valid Array of Object
if (!PipelineQuerySteps) {
throw new Error("Please provide valid Pipeline Steps");
}
return new Aggregation_Operation_1.default(this.name, this.path, PipelineQuerySteps, this.isEncrypted, this.encryptionKey);
}
/**
* Initiates a delete operation on the collection with the provided query.
*
* @param query - The query object that specifies which documents to delete.
* @returns A DeleteOperation instance that can be executed to perform the deletion.
* @throws {Error} Throws an error if the query is empty.
*
* @example
* ```typescript
* // Delete all documents where age is greater than 30
* collection.delete({ age: { $gt: 30 } });
* ```
*/
delete(query) {
// Check if documentId is empty or not
if (!query) {
throw new Error("Query cannot be empty");
}
// Delete the data
return new Delete_operation_1.default(this.name, this.path, query, this.isEncrypted, this.encryptionKey);
}
update(query) {
if (!query) {
throw new Error("Query cannot be empty");
}
return new Update_operation_1.default(this.name, this.path, query, this.isSchemaNeeded, this.schema, this.isEncrypted, this.encryptionKey);
}
}
exports.default = Collection;
//# sourceMappingURL=collection.operation.js.map