feat: add cc-server-db

This commit is contained in:
MiaoWoo 2019-06-11 13:09:50 +08:00
parent 7d84393a3c
commit 73daf1e44e
18 changed files with 129 additions and 87 deletions

View File

@ -1,6 +1,9 @@
{ {
"npmClient": "yarn", "npmClient": "yarn",
"useWorkspaces": true, "useWorkspaces": true,
"scripts": {
"build": "npx tsc"
},
"packages": [ "packages": [
"packages/*" "packages/*"
], ],

View File

@ -11,6 +11,7 @@
}, },
"scripts": { "scripts": {
"dev": "npx ts-node src/index.ts", "dev": "npx ts-node src/index.ts",
"build": "npx tsc",
"test": "echo \"Error: run tests from root\" && exit 1" "test": "echo \"Error: run tests from root\" && exit 1"
}, },
"dependencies": { "dependencies": {
@ -24,6 +25,8 @@
}, },
"devDependencies": { "devDependencies": {
"@types/body-parser": "^1.17.0", "@types/body-parser": "^1.17.0",
"@types/express": "^4.17.0",
"ts-node": "^8.2.0" "ts-node": "^8.2.0"
} },
"gitHead": "7d84393a3cb6be6be9ed51d71f12677d2d7d0728"
} }

View File

@ -1,18 +1,19 @@
import { import {
controller, httpGet, httpPost, httpPut, httpDelete controller, httpGet, httpPost
} from 'inversify-express-utils'; } from 'inversify-express-utils';
import { inject } from 'inversify'; import { inject } from 'inversify';
import { MongoDBClient } from 'cc-server-db-mongo' import { DBClient } from 'cc-server-db'
import 'cc-server-db-mongo'
@controller('/') @controller('/')
export class UserController { export class UserController {
constructor( constructor(
@inject(MongoDBClient) private MongoDBClient: MongoDBClient @inject(DBClient) private client: DBClient
) { } ) { }
@httpGet('/') @httpGet('/')
public async getUsers(): Promise<any[]> { public async getUsers(): Promise<any[]> {
return [] return this.client.find('users', {});
} }
@httpPost('/') @httpPost('/')

View File

@ -1,22 +0,0 @@
{
"compilerOptions": {
"outDir": "dist",
"sourceRoot": "src",
"module": "commonjs",
"target": "es5",
"lib": [
"es6",
"dom"
],
"noImplicitAny": false,
"sourceMap": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"moduleResolution": "node",
"noUnusedLocals": true
},
"compileOnSave": false,
"exclude": [
"node_modules"
]
}

View File

@ -1,19 +1,11 @@
import 'reflect-metadata'; import 'reflect-metadata';
import { InversifyExpressServer } from 'inversify-express-utils'; import { InversifyExpressServer } from 'inversify-express-utils';
import { Container } from 'inversify';
import * as bodyParser from 'body-parser'; import * as bodyParser from 'body-parser';
import { container, buildProviderModule } from 'cc-server-ioc';
import './function/handle'; import './function/handle';
import { METADATA_KEY } from 'cc-server-ioc';
// load everything needed to the Container container.load(buildProviderModule());
let container = new Container();
Reflect.defineMetadata(METADATA_KEY.container, container, Reflect)
// auto load service
let services: Function[] = Reflect.getMetadata(METADATA_KEY.service, Reflect);
for (const service of services) {
service()
}
// start the server // start the server
let server = new InversifyExpressServer(container); let server = new InversifyExpressServer(container);

View File

@ -10,15 +10,19 @@
"registry": "https://repo.yumc.pw/repository/npm-hosted/" "registry": "https://repo.yumc.pw/repository/npm-hosted/"
}, },
"scripts": { "scripts": {
"build": "npx tsc",
"test": "echo \"Error: run tests from root\" && exit 1" "test": "echo \"Error: run tests from root\" && exit 1"
}, },
"dependencies": { "dependencies": {
"cc-server-db": "^0.0.2",
"cc-server-ioc": "^0.0.2", "cc-server-ioc": "^0.0.2",
"inversify": "^5.0.1", "inversify": "^5.0.1",
"mongodb": "^3.2.7", "mongodb": "^3.2.7",
"reflect-metadata": "^0.1.13" "reflect-metadata": "^0.1.13",
"typescript": "^3.5.1"
}, },
"devDependencies": { "devDependencies": {
"@types/mongodb": "^3.1.28" "@types/mongodb": "^3.1.28"
} },
"gitHead": "7d84393a3cb6be6be9ed51d71f12677d2d7d0728"
} }

View File

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

View File

@ -1,7 +1,7 @@
import { Db, MongoClient } from 'mongodb'; import { Db, MongoClient } from 'mongodb';
const connStr = process.env.MONGO_URL || 'mongodb://192.168.0.2:27017'; const connStr = process.env.FAAS_MONGO_URL || 'mongodb://192.168.0.2:27017';
const dbName = process.env.MONGO_DB || "frppool"; const dbName = process.env.FAAS_MONGO_DB || "frppool";
export class MongoDBConnection { export class MongoDBConnection {
private static isConnected: boolean = false; private static isConnected: boolean = false;

4
packages/cc-server-db/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
/node_modules
/dist
/package-lock.json
/yarn.lock

View File

@ -0,0 +1,11 @@
# `cc-server-db`
> TODO: description
## Usage
```
const ccServerDb = require('cc-server-db');
// TODO: DEMONSTRATE API
```

View File

@ -0,0 +1,27 @@
{
"name": "cc-server-db",
"version": "0.0.2",
"description": "Now Im the model of a modern major general / The venerated Virginian veteran whose men are all / Lining up, to put me up on a pedestal / Writin letters to relatives / Embellishin my elegance and eloquence / But the elephant is in the room / The truth is in ya face when ya hear the British cannons go / BOOM",
"keywords": [],
"author": "MiaoWoo <admin@yumc.pw>",
"license": "ISC",
"main": "dist/index.js",
"publishConfig": {
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
},
"repository": {
"type": "git",
"url": "git+https://github.com/502647092/cc-server-parent.git"
},
"scripts": {
"build": "npx tsc",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"bugs": {
"url": "https://github.com/502647092/cc-server-parent/issues"
},
"homepage": "https://github.com/502647092/cc-server-parent#readme",
"dependencies": {
"typescript": "^3.5.1"
}
}

View File

@ -0,0 +1,11 @@
export const DBClient = Symbol.for('DBClient')
export interface DBClient<T = any> {
find(collection: string, filter: object): Promise<T[]>;
findOne(collection: string, filter: Object): Promise<T>;
findOneById(collection: string, objectId: string): Promise<T>;
insertOne(collection: string, model: T): Promise<T>;
updateOne(collection: string, where: any, model: any): Promise<boolean>;
updateById(collection: string, objectId: string, model: any): Promise<boolean>;
deleteOne(collection: string, where: any): Promise<boolean>;
deleteById(collection: string, objectId: string): Promise<boolean>;
}

View File

@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"baseUrl": "src",
"outDir": "dist"
}
}

View File

@ -10,10 +10,14 @@
"registry": "https://repo.yumc.pw/repository/npm-hosted/" "registry": "https://repo.yumc.pw/repository/npm-hosted/"
}, },
"scripts": { "scripts": {
"build": "npx tsc",
"test": "echo \"Error: run tests from root\" && exit 1" "test": "echo \"Error: run tests from root\" && exit 1"
}, },
"dependencies": { "dependencies": {
"inversify": "^5.0.1", "inversify": "^5.0.1",
"reflect-metadata": "^0.1.13" "inversify-binding-decorators": "^4.0.0",
} "reflect-metadata": "^0.1.13",
"typescript": "^3.5.1"
},
"gitHead": "7d84393a3cb6be6be9ed51d71f12677d2d7d0728"
} }

View File

@ -1,4 +0,0 @@
export const METADATA_KEY = {
container: "cc-server-core:container",
service: "cc-server-core:service"
};

View File

@ -1,16 +0,0 @@
import 'reflect-metadata'
import { Container } from 'inversify';
import { METADATA_KEY } from './constant/types';
function service(name: string | symbol) {
return function(target: any) {
let services = Reflect.getMetadata(METADATA_KEY.service, Reflect) || []
services = [() => {
let container: Container = Reflect.getMetadata(METADATA_KEY.container, Reflect)
container.bind(name || target).to(target);
}, ...services]
Reflect.defineMetadata(METADATA_KEY.service, services, Reflect)
}
}
export { service }

View File

@ -1,2 +1,22 @@
export * from './constant/types' import "reflect-metadata";
export * from './decorators' import { Container, inject } from 'inversify';
import { autoProvide, provide, fluentProvide, buildProviderModule } from 'inversify-binding-decorators';
let container = new Container();
// Reflects all decorators provided by this package and packages them into
// a module to be loaded by the container
// container.load(buildProviderModule());
const provideNamed = (identifier, name) => {
return fluentProvide(identifier)
.whenTargetNamed(name)
.done();
};
const provideSingleton = (identifier: any) => {
return fluentProvide(identifier)
.inSingletonScope()
.done();
};
export { container, autoProvide, provide, provideNamed, provideSingleton, inject, buildProviderModule };

View File

@ -1,8 +1,11 @@
{ {
"compilerOptions": { "compilerOptions": {
"baseUrl": "src",
"outDir": "dist",
"target": "es6", "target": "es6",
"module": "commonjs", "module": "commonjs",
"sourceMap": true, "sourceMap": true,
"declaration": true,
"allowUnreachableCode": true, "allowUnreachableCode": true,
"experimentalDecorators": true, "experimentalDecorators": true,
"emitDecoratorMetadata": true "emitDecoratorMetadata": true