Init Project...

This commit is contained in:
2019-06-10 18:56:29 +08:00
commit 1746ffa773
25 changed files with 358 additions and 0 deletions

View File

@@ -0,0 +1,57 @@
import { Db, ObjectID, UpdateWriteOpResult } from 'mongodb';
import { injectable } from 'inversify';
import { MongoDBConnection } from './connection';
import { service } from 'cc-server-ioc'
interface DBClient<T = any> {
find(table: string, where: object): T
}
export const NAME: string = 'MongoDBClient'
@service()
@injectable()
export class MongoDBClient<T = any> implements DBClient {
public db: Db;
constructor() {
MongoDBConnection.getConnection((connection) => {
this.db = connection;
});
}
public find(collection: string, filter: object): Promise<T[]> {
return this.db.collection(collection).find(filter).toArray();
}
public async findOne(collection: string, filter: Object): Promise<T> {
let result = await this.db.collection(collection).find(filter).limit(1).toArray();
return result[0];
}
public async findOneById(collection: string, objectId: string): Promise<T> {
return this.findOne(collection, { _id: new ObjectID(objectId) })
}
public async insertOne(collection: string, model: T): Promise<T> {
var insert = await this.db.collection(collection).insertOne(model);
return insert.ops[0];
}
public updateOne(collection: string, where: any, model: any): Promise<UpdateWriteOpResult> {
return this.db.collection(collection).updateOne(where, { $set: model });
}
public updateById(collection: string, objectId: string, model: any): Promise<UpdateWriteOpResult> {
return this.updateOne(collection, { _id: new ObjectID(objectId) }, { $set: model })
}
public async deleteOne(collection: string, where: any): Promise<boolean> {
let result = await this.db.collection(collection).deleteOne(where);
return result.result.ok === 1 && result.result.n > 0
}
public async deleteById(collection: string, objectId: string): Promise<boolean> {
return this.deleteOne(collection, { _id: new ObjectID(objectId) });
}
}

View File

@@ -0,0 +1,27 @@
import { Db, MongoClient } from 'mongodb';
const connStr = process.env.MONGO_URL || 'mongodb://192.168.0.2:27017';
const dbName = process.env.MONGO_DB || "frppool";
export class MongoDBConnection {
private static isConnected: boolean = false;
private static db: Db;
public static getConnection(result: (connection) => void) {
if (this.isConnected) {
return result(this.db);
} else {
this.connect((error, db: Db) => {
return result(this.db);
});
}
}
private static connect(result: (error, db: Db) => void) {
MongoClient.connect(connStr, { useNewUrlParser: true }, (err, client) => {
this.db = client.db(dbName);
this.isConnected = true;
return result(err, this.db);
});
}
}

View File

@@ -0,0 +1 @@
export * from './client'