Преглед изворни кода

feat(wise-cost-connect): 数据库连接组件

zhangweicheng пре 4 година
родитељ
комит
455eec65fb

+ 11 - 0
wise-cost-connect/.editorconfig

@@ -0,0 +1,11 @@
+# 🎨 editorconfig.org
+
+root = true
+
+[*]
+charset = utf-8
+end_of_line = lf
+indent_style = space
+indent_size = 2
+trim_trailing_whitespace = true
+insert_final_newline = true

+ 7 - 0
wise-cost-connect/.eslintrc.json

@@ -0,0 +1,7 @@
+{
+  "extends": "./node_modules/mwts/",
+  "ignorePatterns": ["node_modules", "dist", "test", "jest.config.js", "typings"],
+  "env": {
+    "jest": true
+  }
+}

+ 15 - 0
wise-cost-connect/.gitignore

@@ -0,0 +1,15 @@
+logs/
+npm-debug.log
+yarn-error.log
+node_modules/
+package-lock.json
+yarn.lock
+coverage/
+dist/
+.idea/
+run/
+.DS_Store
+*.sw*
+*.un~
+.tsbuildinfo
+.tsbuildinfo.*

+ 3 - 0
wise-cost-connect/.prettierrc.js

@@ -0,0 +1,3 @@
+module.exports = {
+  ...require('mwts/.prettierrc.json')
+}

+ 72 - 0
wise-cost-connect/README.md

@@ -0,0 +1,72 @@
+### 开始
+
+wise-cost MongoDB数据库连接组件
+
+组件开发与使用参考midway 组件开发:[http://www.midwayjs.org/doc/component/develop](https://note.youdao.com/)
+
+### 使用组件:
+
+添加依赖:
+```
+// package.json
+{
+  "dependencies": {
+    "@sc/connect": "^1.0.0",
+  },
+}
+```
+然后,在应用中引入这个组件。
+
+```
+// 应用或者函数的 src/configuration.ts
+import { Configuration } from '@midwayjs/decorator';
+import * as connect from '@sc/connect';
+
+@Configuration({
+	imports: [
+  	connect
+  ],
+})
+export class ContainerLifeCycle {
+}
+```
+
+然后在使用的地方引入
+
+```
+import { Provide, Inject } from '@midwayjs/decorator';
+import { MongoDBConnect } from '@sc/connect';
+
+@Provide()
+export class Library {
+
+  @Inject()
+  mongooseDB: MongoDBConnect;
+
+}
+```
+
+同时也像egg-mongoose一样,挂载了 mongoose 和 MongoDBConnect 到 app 下了 
+
+
+### 初始化
+
+npm install
+
+### 构建
+
+
+```
+npm run build
+```
+
+
+### 代码风格
+
+ESLint + Airbnb config
+
+### 发布
+
+发布
+
+`npm publish`

+ 35 - 0
wise-cost-connect/package.json

@@ -0,0 +1,35 @@
+{
+  "name": "@sc/connect",
+  "version": "1.0.0",
+  "description": "",
+  "main": "dist/index.js",
+  "typings": "dist/index.d.ts",
+  "scripts": {
+    "build": "midway-bin build -c",
+    "test": "midway-bin test --ts",
+    "cov": "midway-bin cov --ts",
+    "lint": "mwts check",
+    "lint:fix": "mwts fix"
+  },
+  "keywords": [],
+  "author": "",
+  "files": [
+    "dist/**/*.js",
+    "dist/**/*.d.ts"
+  ],
+  "devDependencies": {
+    "@midwayjs/cli": "^1.2.38",
+    "@midwayjs/core": "^2.3.0",
+    "@midwayjs/decorator": "^2.3.0",
+    "@types/jest": "^26.0.10",
+    "@types/node": "14",
+    "cross-env": "^6.0.0",
+    "globby": "8.0.2",
+    "mongoose": "^6.0.8",
+    "jest": "^26.4.0",
+    "mwts": "^1.0.5",
+    "ts-jest": "^26.2.0",
+    "typescript": "^4.0.0"
+  }
+ 
+}

+ 0 - 0
wise-cost-connect/src/config/config.default.ts


+ 42 - 0
wise-cost-connect/src/configuration.ts

@@ -0,0 +1,42 @@
+// src/configuration.ts
+import { App, Config, Configuration, Logger } from '@midwayjs/decorator';
+import path, { join } from 'path';
+import { ILifeCycle } from '@midwayjs/core';
+import { IMongooseApp, MongoDBConnect } from './connect/mongoDBConnect';
+import * as globby from 'globby';
+
+@Configuration({
+  namespace: 'connect',
+  importConfigs: [join(__dirname, 'config')],
+})
+export class AutoConfiguration implements ILifeCycle {
+  @App()
+  app: IMongooseApp;
+
+  @Config('mongoose')
+  mongoDBConfig;
+
+  @Config('baseDir')
+  baseDir: string;
+
+  @Logger()
+  logger;
+
+  async onReady() {
+    const connect = new MongoDBConnect(this.mongoDBConfig, this.app); //生成连接对像
+    this.app.getApplicationContext().registerObject('mongooseDB', connect); //注册到app中
+    this.loadModelFile(); //加载model文件
+  }
+
+  loadModelFile() {
+    const dir = path.join(this.baseDir, 'app/model');
+    const files: string[] = globby.sync(['**/*.(js|ts)', '!**/*.d.ts'], {
+      cwd: dir,
+    });
+    files.forEach(filePath => require(path.join(dir, filePath))(this.app));
+  }
+  async onStop(): Promise<void> {
+    // 关闭数据库连接
+    await this.app.mongooseDB.closeDB();
+  }
+}

+ 58 - 0
wise-cost-connect/src/connect/mongoDBConnect.ts

@@ -0,0 +1,58 @@
+import { IMidwayApplication } from '@midwayjs/core';
+import { Inject } from '@midwayjs/decorator';
+import mongoose, { Connection, ConnectOptions, Mongoose } from 'mongoose';
+
+export interface IMongooseApp extends IMidwayApplication {
+  mongoose: Mongoose;
+  mongooseDB: MongoDBConnect;
+}
+
+export class MongoDBConnect {
+  @Inject()
+  logger;
+
+  private clients: Map<string, Connection>;
+
+  private newConnection(
+    name = 'default',
+    config: { url: string; options: ConnectOptions }
+  ) {
+    const { url, options } = config;
+    if (!url) {
+      return this.logger.error('url 不能为空!');
+    }
+    const conn = mongoose.createConnection(url, options);
+    this.clients[name] = conn;
+  }
+
+  private createClients(config: any) {
+    const { client, clients } = config;
+    if (client) {
+      this.newConnection(client.name, client);
+    }
+
+    if (clients) {
+      Object.keys(clients).forEach(dbName =>
+        this.newConnection(dbName, clients[dbName])
+      );
+    }
+  }
+
+  constructor(config: any, app: IMongooseApp) {
+    this.clients = new Map();
+    this.createClients(config);
+    app.mongoose = mongoose;
+    app.mongooseDB = this;
+  }
+
+  get(dbName: string) {
+    return this.clients[dbName];
+  }
+
+  async closeDB() {
+    const connects: Connection[] = Object.values(this.clients);
+    for (const connect of connects) {
+      await connect.close();
+    }
+  }
+}

+ 2 - 0
wise-cost-connect/src/index.ts

@@ -0,0 +1,2 @@
+export { AutoConfiguration as Configuration } from './configuration';
+export * from './connect/mongoDBConnect';

+ 3 - 0
wise-cost-connect/test/index.test.ts

@@ -0,0 +1,3 @@
+describe('/test/index.test.ts', () => {
+  it('test component', () => {});
+});

+ 25 - 0
wise-cost-connect/tsconfig.json

@@ -0,0 +1,25 @@
+{
+  "compileOnSave": true,
+  "compilerOptions": {
+    "target": "ES2018",
+    "module": "commonjs",
+    "moduleResolution": "node",
+    "experimentalDecorators": true,
+    "emitDecoratorMetadata": true,
+    "inlineSourceMap":false,
+    "noImplicitThis": true,
+    "esModuleInterop": true,
+    "noUnusedLocals": true,
+    "stripInternal": true,
+    "skipLibCheck": false,
+    "noImplicitReturns": false,
+    "pretty": true,
+    "declaration": true,
+    "outDir": "dist"
+  },
+  "exclude": [
+    "dist",
+    "node_modules",
+    "test"
+  ]
+}