feat: remove auto connect use manual inject

Signed-off-by: MiaoWoo <admin@yumc.pw>
This commit is contained in:
2019-10-18 14:26:26 +08:00
parent 5fa5603735
commit 140f881062
8 changed files with 37 additions and 50 deletions

View File

@@ -1,31 +1,15 @@
import { DBClient } from '@cc-server/db'
import { MongoDBConnection } from './connection'
import { Db, ObjectID, Collection } from 'mongodb'
import { provide, postConstruct } from '@cc-server/ioc'
import { ObjectID, Collection } from 'mongodb'
@provide(DBClient)
export class MongoDBClient<T = any> implements DBClient {
private table: string;
private db: Db;
export class MongoCollection<T = any> implements DBClient {
private collection: Collection<T>;
@postConstruct()
private async init() {
this.db = await MongoDBConnection.getConnection();
if (this.table) {
this.collection = this.db.collection(this.table);
}
constructor(collection: Collection<T>) {
this.collection = collection;
}
public getProvide<P>(): P {
return this.db as {} as P;
}
public setTable(table: string): void {
this.table = table;
if (this.db) {
this.collection = this.db.collection(table);
}
return this.collection as {} as P;
}
public async find(filter: object): Promise<T[]> {

View File

@@ -1,18 +0,0 @@
import { Db, MongoClient } from 'mongodb';
const connStr = process.env.FAAS_MONGO_URL || 'mongodb://192.168.0.2:27017';
const dbName = process.env.FAAS_MONGO_DB || "faas";
export class MongoDBConnection {
private static db: Db;
public static async getConnection(): Promise<Db> {
if (!this.db) { this.db = await this.connect() }
return this.db;
}
private static async connect(): Promise<Db> {
let client = await MongoClient.connect(connStr, { useNewUrlParser: true });
return client.db(dbName);
}
}

View File

@@ -0,0 +1,7 @@
export const TYPE = {
URL: Symbol.for('URL'),
DB: Symbol.for('DB'),
Client: Symbol.for('Client'),
Database: Symbol.for('Database'),
Collection: Symbol.for('Collection')
}

View File

@@ -1,2 +1,3 @@
export * from 'mongodb'
export * from './client'
export * from './constants'