-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
244 lines (207 loc) · 7.15 KB
/
index.js
File metadata and controls
244 lines (207 loc) · 7.15 KB
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
// mingleDB.js - Lightweight File-Based NoSQL Engine with Compression, Schema, Query, and Basic Authentication Support
const fs = require("fs");
const path = require("path");
const BSON = require("bson");
const zlib = require("zlib");
const crypto = require("crypto");
const HEADER = Buffer.from("MINGLEDBv1");
const MINGLEDB_EXTENSIONS = ".mgdb";
class MingleDB {
constructor(dbDir = ".mgdb") {
this.dbDir = dbDir;
this.schemas = {};
this.authenticatedUsers = new Set();
if (!fs.existsSync(dbDir)) fs.mkdirSync(dbDir);
}
/**
* 🧹 Completely wipe all collections and reset schemas/auth state.
* Useful for unit testing or a full reset.
*/
reset() {
if (fs.existsSync(this.dbDir)) {
// remove all .mingleDB files
for (const file of fs.readdirSync(this.dbDir)) {
if (file.endsWith(MINGLEDB_EXTENSIONS)) {
fs.unlinkSync(path.join(this.dbDir, file));
}
}
}
this.schemas = {};
this.authenticatedUsers.clear();
}
defineSchema(collection, schemaDefinition) {
this.schemas[collection] = schemaDefinition;
}
registerUser(username, password) {
this._initCollectionFile("_auth");
const users = this.findAll("_auth");
const exists = users.find((u) => u.username === username);
if (exists) throw new Error("Username already exists.");
const hashed = this._hashPassword(password);
this.insertOne("_auth", { username, password: hashed });
}
login(username, password) {
const user = this.findOne("_auth", { username });
if (!user || user.password !== this._hashPassword(password)) {
throw new Error("Authentication failed.");
}
this.authenticatedUsers.add(username);
return true;
}
isAuthenticated(username) {
return this.authenticatedUsers.has(username);
}
logout(username) {
this.authenticatedUsers.delete(username);
}
_hashPassword(password) {
return crypto.createHash("sha256").update(password).digest("hex");
}
_getFilePath(collection) {
return path.join(this.dbDir, `${collection}${MINGLEDB_EXTENSIONS}`);
}
_initCollectionFile(collection) {
const filePath = this._getFilePath(collection);
if (!fs.existsSync(filePath)) {
const meta = Buffer.from(JSON.stringify({ collection }));
const metaLen = Buffer.alloc(4);
metaLen.writeUInt32LE(meta.length);
fs.writeFileSync(filePath, Buffer.concat([HEADER, metaLen, meta]));
}
}
_validateSchema(collection, doc) {
const schema = this.schemas[collection];
if (!schema) return;
for (const key in schema) {
const rule = schema[key];
const value = doc[key];
if (rule.required && (value === undefined || value === null)) {
throw new Error(`Validation error: Field "${key}" is required.`);
}
if (value !== undefined && typeof value !== rule.type) {
throw new Error(
`Validation error: Field "${key}" must be of type ${rule.type}.`,
);
}
if (rule.unique && value !== undefined) {
const all = this.findAll(collection);
const duplicate = all.find((d) => d[key] === value);
if (duplicate) {
throw new Error(
`Validation error: Duplicate value for unique field "${key}".`,
);
}
}
}
}
insertOne(collection, doc) {
this._initCollectionFile(collection);
this._validateSchema(collection, doc);
const filePath = this._getFilePath(collection);
const bson = BSON.serialize(doc);
const compressed = zlib.deflateSync(bson);
const length = Buffer.alloc(4);
length.writeUInt32LE(compressed.length);
fs.appendFileSync(filePath, Buffer.concat([length, compressed]));
}
findAll(collection) {
const filePath = this._getFilePath(collection);
if (!fs.existsSync(filePath)) return [];
const buffer = fs.readFileSync(filePath);
const docs = [];
let offset = HEADER.length;
const metaLen = buffer.readUInt32LE(offset);
offset += 4 + metaLen;
while (offset < buffer.length) {
const len = buffer.readUInt32LE(offset);
offset += 4;
const compressedBuf = buffer.slice(offset, offset + len);
offset += len;
const bson = zlib.inflateSync(compressedBuf);
docs.push(BSON.deserialize(bson));
}
return docs;
}
find(collection, filter = {}) {
const docs = this.findAll(collection);
return docs.filter((doc) => this._matchQuery(doc, filter));
}
findOne(collection, filter = {}) {
return this.find(collection, filter)[0] || null;
}
deleteOne(collection, query) {
const all = this.findAll(collection);
const newDocs = [];
let deleted = false;
for (const doc of all) {
if (!deleted && this._matchQuery(doc, query)) {
deleted = true;
continue;
}
newDocs.push(doc);
}
this._rewriteCollection(collection, newDocs);
return deleted;
}
updateOne(collection, query, update) {
const all = this.findAll(collection);
let updated = false;
const updatedDocs = all.map((doc) => {
if (!updated && this._matchQuery(doc, query)) {
updated = true;
return { ...doc, ...update };
}
return doc;
});
this._rewriteCollection(collection, updatedDocs);
return updated;
}
_rewriteCollection(collection, docs) {
const filePath = this._getFilePath(collection);
const meta = Buffer.from(JSON.stringify({ collection }));
const metaLen = Buffer.alloc(4);
metaLen.writeUInt32LE(meta.length);
const docBuffers = docs.map((doc) => {
const bson = BSON.serialize(doc);
const compressed = zlib.deflateSync(bson);
const len = Buffer.alloc(4);
len.writeUInt32LE(compressed.length);
return Buffer.concat([len, compressed]);
});
fs.writeFileSync(
filePath,
Buffer.concat([HEADER, metaLen, meta, ...docBuffers]),
);
}
_matchQuery(doc, query) {
return Object.entries(query).every(([key, value]) => {
const docVal = doc[key];
if (value instanceof RegExp) {
return typeof docVal === "string" && value.test(docVal);
}
if (typeof value === "object" && value !== null) {
if ("$gt" in value && !(docVal > value.$gt)) return false;
if ("$gte" in value && !(docVal >= value.$gte)) return false;
if ("$lt" in value && !(docVal < value.$lt)) return false;
if ("$lte" in value && !(docVal <= value.$lte)) return false;
if ("$eq" in value && !(docVal === value.$eq)) return false;
if ("$ne" in value && !(docVal !== value.$ne)) return false;
if ("$in" in value && !value.$in.includes(docVal)) return false;
if ("$nin" in value && value.$nin.includes(docVal)) return false;
if ("$regex" in value) {
const pattern = typeof value.$regex === "string" ? value.$regex : String(value.$regex);
const flags = typeof value.$options === "string" && value.$options.includes("i") ? "i" : "";
try {
const re = new RegExp(pattern, flags);
return typeof docVal === "string" && re.test(docVal);
} catch {
return false;
}
}
return true;
}
return docVal === value;
});
}
}
module.exports = MingleDB;