Skip to content

Commit 5f19642

Browse files
committed
add db.table constructor
1 parent 9064244 commit 5f19642

2 files changed

Lines changed: 45 additions & 3 deletions

File tree

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "quickmongo",
3-
"version": "5.0.1",
3+
"version": "5.1.0",
44
"description": "Quick Mongodb wrapper for beginners that provides key-value based interface.",
55
"main": "dist/index.js",
66
"module": "dist/index.mjs",

src/Database.ts

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,6 @@ interface QmEvents<V = unknown> {
6666
fullsetup: () => unknown;
6767
all: () => unknown;
6868
reconnectFailed: () => unknown;
69-
reconnectTries: () => unknown;
7069
}
7170

7271
/**
@@ -297,7 +296,7 @@ export class Database<T = unknown, PAR = unknown> extends TypedEmitter<QmEvents<
297296
}
298297

299298
/**
300-
* Create a child database (similar to quick.db table)
299+
* Create a child database, either from new connection or current connection (similar to quick.db table)
301300
* @param {?string} collection The collection name (defaults to `JSON`)
302301
* @param {?string} url The database url (not needed if the child needs to share connection from parent)
303302
* @returns {Promise<Database>}
@@ -317,6 +316,45 @@ export class Database<T = unknown, PAR = unknown> extends TypedEmitter<QmEvents<
317316
return ndb;
318317
}
319318

319+
/**
320+
* Identical to quick.db table
321+
* @type {Database}
322+
* @example const table = new db.table("table");
323+
* table.set("foo", "Bar");
324+
*/
325+
public get table() {
326+
return new Proxy(
327+
function () {
328+
/* noop */
329+
} as unknown as TableConstructor,
330+
{
331+
construct: (_, args) => {
332+
const name = args[0];
333+
if (!name || typeof name !== "string") throw new TypeError("ERR_TABLE_NAME");
334+
const db = new Database(this.url, this.options);
335+
336+
db.connection = this.connection;
337+
db.model = modelSchema(this.connection, name);
338+
db.connect = () => Promise.resolve(db);
339+
340+
Object.defineProperty(db, "table", {
341+
get() {
342+
return;
343+
},
344+
set() {
345+
return;
346+
}
347+
});
348+
349+
return db;
350+
},
351+
apply: () => {
352+
throw new Error("TABLE_IS_NOT_A_FUNCTION");
353+
}
354+
}
355+
);
356+
}
357+
320358
/**
321359
* Returns everything from the database
322360
* @param {?AllQueryOptions} options The request options
@@ -523,6 +561,10 @@ export class Database<T = unknown, PAR = unknown> extends TypedEmitter<QmEvents<
523561
}
524562
}
525563

564+
export interface TableConstructor<V = unknown> {
565+
new (name: string): Database<V>;
566+
}
567+
526568
/**
527569
* Emitted once the database is ready
528570
* @event Database#ready

0 commit comments

Comments
 (0)