Skip to content

Commit

Permalink
add db.table constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
twlite committed Jan 21, 2022
1 parent 9064244 commit 5f19642
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 3 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "quickmongo",
"version": "5.0.1",
"version": "5.1.0",
"description": "Quick Mongodb wrapper for beginners that provides key-value based interface.",
"main": "dist/index.js",
"module": "dist/index.mjs",
Expand Down
46 changes: 44 additions & 2 deletions src/Database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ interface QmEvents<V = unknown> {
fullsetup: () => unknown;
all: () => unknown;
reconnectFailed: () => unknown;
reconnectTries: () => unknown;
}

/**
Expand Down Expand Up @@ -297,7 +296,7 @@ export class Database<T = unknown, PAR = unknown> extends TypedEmitter<QmEvents<
}

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

/**
* Identical to quick.db table
* @type {Database}
* @example const table = new db.table("table");
* table.set("foo", "Bar");
*/
public get table() {
return new Proxy(
function () {
/* noop */
} as unknown as TableConstructor,
{
construct: (_, args) => {
const name = args[0];
if (!name || typeof name !== "string") throw new TypeError("ERR_TABLE_NAME");
const db = new Database(this.url, this.options);

db.connection = this.connection;
db.model = modelSchema(this.connection, name);
db.connect = () => Promise.resolve(db);

Object.defineProperty(db, "table", {
get() {
return;
},
set() {
return;
}
});

return db;
},
apply: () => {
throw new Error("TABLE_IS_NOT_A_FUNCTION");
}
}
);
}

/**
* Returns everything from the database
* @param {?AllQueryOptions} options The request options
Expand Down Expand Up @@ -523,6 +561,10 @@ export class Database<T = unknown, PAR = unknown> extends TypedEmitter<QmEvents<
}
}

export interface TableConstructor<V = unknown> {
new (name: string): Database<V>;
}

/**
* Emitted once the database is ready
* @event Database#ready
Expand Down

0 comments on commit 5f19642

Please sign in to comment.