1
0
Fork 0
cc-server-parent/packages/cc-server-db-mongo/src/client/index.ts

68 lines
2.0 KiB
TypeScript
Raw Normal View History

2019-06-11 10:49:06 +00:00
import { Db, ObjectID, Collection } from 'mongodb';
2019-06-10 10:56:29 +00:00
import { MongoDBConnection } from './connection';
2019-06-11 05:09:50 +00:00
import { provide } from 'cc-server-ioc'
import { DBClient } from 'cc-server-db'
2019-06-10 10:56:29 +00:00
2019-06-11 05:09:50 +00:00
@provide(DBClient)
2019-06-11 08:11:34 +00:00
export class MongoDBClient<T = any> implements DBClient {
2019-06-12 05:33:31 +00:00
private table: string;
2019-06-11 10:49:06 +00:00
private db: Db;
private collection: Collection;
2019-06-10 10:56:29 +00:00
constructor() {
MongoDBConnection.getConnection((connection) => {
this.db = connection;
2019-06-12 05:33:31 +00:00
if (this.table) {
this.collection = this.db.collection(this.table);
}
2019-06-10 10:56:29 +00:00
});
}
2019-06-11 08:11:34 +00:00
public getProvide(): Db {
return this.db;
}
2019-06-11 10:49:06 +00:00
public setTable(table: string): void {
2019-06-12 05:33:31 +00:00
this.table = table;
if (this.db) {
this.collection = this.db.collection(table);
}
2019-06-10 10:56:29 +00:00
}
2019-06-11 10:49:06 +00:00
public async find(filter: object): Promise<T[]> {
return await this.collection.find(filter).toArray();
}
public async findOne(filter: Object): Promise<T> {
let result = await this.collection.find(filter).limit(1).toArray();
2019-06-10 10:56:29 +00:00
return result[0];
}
2019-06-11 10:49:06 +00:00
public async findOneById(objectId: string): Promise<T> {
return await this.findOne({ _id: new ObjectID(objectId) })
2019-06-10 10:56:29 +00:00
}
2019-06-11 10:49:06 +00:00
public async insertOne(model: T): Promise<T> {
var insert = await this.collection.insertOne(model);
2019-06-10 10:56:29 +00:00
return insert.ops[0];
}
2019-06-11 10:49:06 +00:00
public async updateOne(where: any, model: any): Promise<boolean> {
let result = await this.collection.updateOne(where, { $set: model });
2019-06-11 05:09:50 +00:00
return result.result.ok == 1 && result.result.n > 0;
2019-06-10 10:56:29 +00:00
}
2019-06-11 10:49:06 +00:00
public async updateById(objectId: string, model: any): Promise<boolean> {
return await this.updateOne({ _id: new ObjectID(objectId) }, { $set: model })
2019-06-10 10:56:29 +00:00
}
2019-06-11 10:49:06 +00:00
public async deleteOne(where: any): Promise<boolean> {
let result = await this.collection.deleteOne(where);
2019-06-10 10:56:29 +00:00
return result.result.ok === 1 && result.result.n > 0
}
2019-06-11 10:49:06 +00:00
public async deleteById(objectId: string): Promise<boolean> {
return this.deleteOne({ _id: new ObjectID(objectId) });
2019-06-10 10:56:29 +00:00
}
}