lrf402788946 4 years ago
commit
8a5279889d

+ 29 - 0
.autod.conf.js

@@ -0,0 +1,29 @@
+'use strict';
+
+module.exports = {
+  write: true,
+  prefix: '^',
+  plugin: 'autod-egg',
+  test: [
+    'test',
+    'benchmark',
+  ],
+  dep: [
+    'egg',
+    'egg-scripts',
+  ],
+  devdep: [
+    'egg-ci',
+    'egg-bin',
+    'egg-mock',
+    'autod',
+    'autod-egg',
+    'eslint',
+    'eslint-config-egg',
+  ],
+  exclude: [
+    './test/fixtures',
+    './dist',
+  ],
+};
+

+ 1 - 0
.eslintignore

@@ -0,0 +1 @@
+coverage

+ 3 - 0
.eslintrc

@@ -0,0 +1,3 @@
+{
+  "extends": "eslint-config-egg"
+}

+ 42 - 0
.github/workflows/nodejs.yml

@@ -0,0 +1,42 @@
+# This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node
+# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
+
+name: Node.js CI
+
+on:
+  push:
+    branches: [ master ]
+  pull_request:
+    branches: [ master ]
+  schedule:
+    - cron: '0 2 * * *'
+
+jobs:
+  build:
+    runs-on: ${{ matrix.os }}
+
+    strategy:
+      fail-fast: false
+      matrix:
+        node-version: [10]
+        os: [ubuntu-latest, windows-latest, macos-latest]
+
+    steps:
+    - name: Checkout Git Source
+      uses: actions/checkout@v2
+
+    - name: Use Node.js ${{ matrix.node-version }}
+      uses: actions/setup-node@v1
+      with:
+        node-version: ${{ matrix.node-version }}
+
+    - name: Install Dependencies
+      run: npm i -g npminstall && npminstall
+
+    - name: Continuous Integration
+      run: npm run ci
+
+    - name: Code Coverage
+      uses: codecov/codecov-action@v1
+      with:
+        token: ${{ secrets.CODECOV_TOKEN }}

+ 14 - 0
.gitignore

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

+ 12 - 0
.travis.yml

@@ -0,0 +1,12 @@
+
+language: node_js
+node_js:
+  - '10'
+before_install:
+  - npm i npminstall -g
+install:
+  - npminstall
+script:
+  - npm run ci
+after_script:
+  - npminstall codecov && codecov

+ 33 - 0
README.md

@@ -0,0 +1,33 @@
+# middle-service
+
+中间层
+
+## QuickStart
+
+<!-- add docs here for user -->
+
+see [egg docs][egg] for more detail.
+
+### Development
+
+```bash
+$ npm i
+$ npm run dev
+$ open http://localhost:7001/
+```
+
+### Deploy
+
+```bash
+$ npm start
+$ npm stop
+```
+
+### npm scripts
+
+- Use `npm run lint` to check code style.
+- Use `npm test` to run unit test.
+- Use `npm run autod` to auto detect dependencies upgrade, see [autod](https://www.npmjs.com/package/autod) for more detail.
+
+
+[egg]: https://eggjs.org

+ 12 - 0
app/controller/home.js

@@ -0,0 +1,12 @@
+'use strict';
+
+const Controller = require('egg').Controller;
+
+class HomeController extends Controller {
+  async index() {
+    const { ctx } = this;
+    ctx.body = 'hi, egg';
+  }
+}
+
+module.exports = HomeController;

+ 22 - 0
app/controller/request.js

@@ -0,0 +1,22 @@
+'use strict';
+const Controller = require('egg').Controller;
+const { CrudController } = require('naf-framework-mongoose/lib/controller');
+
+// 请求处理
+class RequestController extends Controller {
+  constructor(ctx) {
+    super(ctx);
+    this.util = this.ctx.service.util.util;
+    this.httpUtil = this.ctx.service.util.httpUtil;
+  }
+  async index() {
+    const { url, body, method } = this.util.analyzeUrl();
+    // query和url已经合并,没有query了,所以直接body,get方法第二个位置不需要了,也不会传值来(传来就是找茬)
+    // create,post,delete都有可能传,而且第二个位置都是body
+    const res = await this.httpUtil[`$${method}`](url, body);
+    // TODO,此处应该设置再处理名单,若在名单中,则继续处理数据,否则透传
+    this.ctx.body = res;
+    // this.ctx.ok();
+  }
+}
+module.exports = CrudController(RequestController, {});

+ 14 - 0
app/controller/stoken.js

@@ -0,0 +1,14 @@
+'use strict';
+const Controller = require('egg').Controller;
+const { CrudController } = require('naf-framework-mongoose/lib/controller');
+
+// stoken
+class StokenController extends Controller {
+  async getToken() {
+    this.ctx.ok();
+  }
+  async checkToken() {
+    this.ctx.ok();
+  }
+}
+module.exports = CrudController(StokenController, {});

+ 18 - 0
app/controller/test.js

@@ -0,0 +1,18 @@
+'use strict';
+const Controller = require('egg').Controller;
+const { CrudController } = require('naf-framework-mongoose/lib/controller');
+
+//
+class TestController extends Controller {
+  constructor(ctx) {
+    super(ctx);
+    this.util = this.ctx.service.util.util;
+  }
+  async index() {
+    console.log('in function:');
+    console.log(this.ctx.request);
+    this.ctx.ok();
+  }
+}
+// 令牌机制:
+module.exports = CrudController(TestController, {});

+ 9 - 0
app/middleware/stoken.js

@@ -0,0 +1,9 @@
+'use strict';
+const _ = require('lodash');
+const { ObjectId } = require('mongoose').Types;
+module.exports = options => {
+  return async function stoken(ctx, next) {
+    await next();
+    ctx.body.stoken = ctx.csrf;
+  };
+};

+ 16 - 0
app/router.js

@@ -0,0 +1,16 @@
+'use strict';
+
+/**
+ * @param {Egg.Application} app - egg application
+ */
+module.exports = app => {
+  const { router, controller } = app;
+  router.get('/', controller.home.index);
+  const stoken = app.middleware.stoken();
+  router.get('/api/m/stoken', stoken, controller.stoken.getToken);
+  router.post('/api/m/checkToken', controller.stoken.checkToken);
+  router.delete('/api/m/checkToken', controller.stoken.checkToken);
+  router.get(/^\/api\/m*/, controller.request.index);
+  router.post(/^\/api\/m*/, controller.request.index);
+  router.delete(/^\/api\/m*/, controller.request.index);
+};

+ 97 - 0
app/service/util/http-util.js

@@ -0,0 +1,97 @@
+'use strict';
+const _ = require('lodash');
+const { AxiosService } = require('naf-framework-mongoose/lib/service');
+const { BusinessError, ErrorCode } = require('naf-core').Error;
+const { isNullOrUndefined } = require('naf-core').Util;
+
+class UtilService extends AxiosService {
+  constructor(ctx) {
+    super(ctx, {}, {});
+  }
+
+  // 替换uri中的参数变量
+  merge(uri, query = {}) {
+    const keys = Object.keys(query);
+    const arr = [];
+    for (const k of keys) {
+      arr.push(`${k}=${query[k]}`);
+    }
+    if (arr.length > 0) {
+      uri = `${uri}?${arr.join('&')}`;
+    }
+    return uri;
+  }
+
+  /**
+   * curl-get请求
+   * @param {String} uri 接口地址
+   * @param {Object} query 地址栏参数
+   * @param {Object} options 额外参数
+   */
+  async $get(uri, query, options) {
+    return this.toRequest(uri, null, query, options);
+  }
+
+  /**
+   * curl-post请求
+   * @param {String} uri 接口地址
+   * @param {Object} data post的body
+   * @param {Object} query 地址栏参数
+   * @param {Object} options 额外参数
+   */
+  async $post(uri, data = {}, query, options) {
+    return this.toRequest(uri, data, query, options);
+  }
+
+  /**
+   * curl-delete请求
+   * @param {String} uri 接口地址
+   * @param {Object} data post的body
+   * @param {Object} query 地址栏参数
+   * @param {Object} options 额外参数默认 method:delete
+   */
+  async $delete(uri, data = {}, query, options) {
+    options = { ...options, method: 'delete' };
+    return this.toRequest(uri, data, query, options);
+  }
+
+  async toRequest(uri, data, query, options) {
+    query = _.pickBy(
+      query,
+      val => val !== '' && val !== 'undefined' && val !== 'null'
+    );
+    if (!uri) console.error('uri不能为空');
+    if (_.isObject(query) && _.isObject(options)) {
+      const params = query.params ? query.params : query;
+      options = { ...options, params };
+    } else if (_.isObject(query) && !query.params) {
+      options = { params: query };
+    } else if (_.isObject(query) && query.params) {
+      options = query;
+    }
+    // 是否多租户模式,需要改变headers
+    const headers = { 'content-type': 'application/json' };
+    let url = this.merge(`${uri}`, options.params);
+    if (!url.includes('http')) url = `http://127.0.0.1${url}`;
+    let res = await this.ctx.curl(url, {
+      method: isNullOrUndefined(data) ? 'get' : 'post',
+      url,
+      data,
+      dataType: 'json',
+      headers,
+      ...options,
+    });
+    if (res.status === 200) {
+      res = res.data || {};
+      const { errcode, errmsg, details } = res;
+      if (errcode) {
+        console.warn(`[${uri}] fail: ${errcode}-${errmsg} ${details}`);
+        return { errcode, errmsg };
+      }
+      return res;
+    }
+    const { status } = res;
+    console.warn(`[${uri}] fail: ${status}-${res.data.message} `);
+  }
+}
+module.exports = UtilService;

+ 96 - 0
app/service/util/util.js

@@ -0,0 +1,96 @@
+'use strict';
+const _ = require('lodash');
+const moment = require('moment');
+const { CrudService } = require('naf-framework-mongoose/lib/service');
+const { ObjectId } = require('mongoose').Types;
+const { BusinessError, ErrorCode } = require('naf-core').Error;
+const fs = require('fs');
+class UtilService extends CrudService {
+  constructor(ctx) {
+    super(ctx);
+    this.mq = this.ctx.mq;
+    this.projectList = this.app.config.project;
+  }
+  async utilMethod(query, body) {}
+
+  dealQuery(query) {
+    return this.turnFilter(this.turnDateRangeQuery(query));
+  }
+
+  analyzeUrl() {
+    const request = this.ctx.request;
+    let { method, url } = request;
+    method = _.lowerCase(method);
+    if (url.includes('/api/m/site')) {
+      // TODO 通过网站进来的,如果是GET方法=>计数;然后将site去掉
+      url = url.replace('/site', '');
+    }
+    const nUrl = this.dealUrl(url);
+    const res = { url: nUrl, method };
+    // 处理body
+    if (method === 'post' || method === 'delete') {
+      res.body = this.ctx.request.body;
+    }
+    return res;
+  }
+
+  dealUrl(url) {
+    let arr = url.split('/');
+    // 前3个属于中间层入口,干掉,直接干掉
+    arr = _.drop(arr, 3);
+    // 取出项目
+    const project = _.head(arr);
+    const uri = `/${_.drop(arr, 1).join('/')}`;
+    const prefix = this.projectList[project];
+    if (!prefix) throw new BusinessError(ErrorCode.SERVICE_FAULT, '未设置该project');
+    return `${prefix}${uri}`;
+  }
+
+  /**
+   * 将查询条件中模糊查询的标识转换成对应object
+   * @param {Object} filter 查询条件
+   */
+  turnFilter(filter) {
+    const str = /^%\S*%$/;
+    const keys = Object.keys(filter);
+    for (const key of keys) {
+      const res = key.match(str);
+      if (res) {
+        const newKey = key.slice(1, key.length - 1);
+        filter[newKey] = new RegExp(filter[key]);
+        delete filter[key];
+      }
+    }
+    return filter;
+  }
+  /**
+   * 将时间转换成对应查询Object
+   * @param {Object} filter 查询条件
+   */
+  turnDateRangeQuery(filter) {
+    const keys = Object.keys(filter);
+    for (const k of keys) {
+      if (k.includes('@')) {
+        const karr = k.split('@');
+        //  因为是针对处理范围日期,所以必须只有,开始时间和结束时间
+        if (karr.length === 2) {
+          const type = karr[1];
+          if (type === 'start') {
+            filter[karr[0]] = {
+              ..._.get(filter, karr[0], {}),
+              $gte: filter[k],
+            };
+          } else {
+            filter[karr[0]] = {
+              ..._.get(filter, karr[0], {}),
+              $lte: filter[k],
+            };
+          }
+          delete filter[k];
+        }
+      }
+    }
+    return filter;
+  }
+}
+module.exports = UtilService;

+ 14 - 0
appveyor.yml

@@ -0,0 +1,14 @@
+environment:
+  matrix:
+    - nodejs_version: '10'
+
+install:
+  - ps: Install-Product node $env:nodejs_version
+  - npm i npminstall && node_modules\.bin\npminstall
+
+test_script:
+  - node --version
+  - npm --version
+  - npm run test
+
+build: off

+ 46 - 0
config/config.default.js

@@ -0,0 +1,46 @@
+/* eslint valid-jsdoc: "off" */
+
+'use strict';
+
+/**
+ * @param {Egg.EggAppInfo} appInfo app info
+ */
+module.exports = appInfo => {
+  /**
+   * built-in config
+   * @type {Egg.EggAppConfig}
+   **/
+  const config = exports = {};
+
+  // use for cookie sign key, should change to your own and keep security
+  config.keys = appInfo.name + '_1618556380571_5956';
+
+  // add your middleware config here
+  config.middleware = [ ];
+
+  // add your user config here
+  const userConfig = {
+    // myAppName: 'egg',
+  };
+  config.cluster = {
+    listen: {
+      port: 9200,
+    },
+  };
+  config.security = {
+    csrf: {
+      enable: false,
+      type: 'ctoken',
+      useSession: true,
+    },
+  };
+
+  config.project = {
+    main: 'http://127.0.0.1:9201',
+  };
+
+  return {
+    ...config,
+    ...userConfig,
+  };
+};

+ 9 - 0
config/plugin.js

@@ -0,0 +1,9 @@
+'use strict';
+
+/** @type Egg.EggPlugin */
+module.exports = {
+  // had enabled by egg
+  // static: {
+  //   enable: true,
+  // }
+};

+ 51 - 0
package.json

@@ -0,0 +1,51 @@
+{
+  "name": "middle-service",
+  "version": "1.0.0",
+  "description": "中间层",
+  "private": true,
+  "egg": {
+    "framework": "naf-framework-mongoose"
+  },
+  "dependencies": {
+    "egg": "^2.15.1",
+    "egg-scripts": "^2.11.0",
+    "egg-naf-amqp": "0.0.13",
+    "egg-redis": "^2.4.0",
+    "lodash": "^4.17.15",
+    "moment": "^2.24.0",
+    "naf-framework-mongoose": "^0.6.11"
+  },
+  "devDependencies": {
+    "autod": "^3.0.1",
+    "autod-egg": "^1.1.0",
+    "egg-bin": "^4.11.0",
+    "egg-ci": "^1.11.0",
+    "egg-mock": "^3.21.0",
+    "eslint": "^5.13.0",
+    "eslint-config-egg": "^7.1.0"
+  },
+  "engines": {
+    "node": ">=10.0.0"
+  },
+  "scripts": {
+    "start": "egg-scripts start --daemon --title=egg-server-middle-service",
+    "stop": "egg-scripts stop --title=egg-server-middle-service",
+    "dev": "egg-bin dev",
+    "debug": "egg-bin debug",
+    "test": "npm run lint -- --fix && npm run test-local",
+    "test-local": "egg-bin test",
+    "cov": "egg-bin cov",
+    "lint": "eslint .",
+    "ci": "npm run lint && npm run cov",
+    "autod": "autod"
+  },
+  "ci": {
+    "version": "10"
+  },
+  "repository": {
+    "type": "git",
+    "url": ""
+  },
+  "author": "lrf",
+  "license": "MIT"
+}

+ 20 - 0
test/app/controller/home.test.js

@@ -0,0 +1,20 @@
+'use strict';
+
+const { app, assert } = require('egg-mock/bootstrap');
+
+describe('test/app/controller/home.test.js', () => {
+  it('should assert', () => {
+    const pkg = require('../../../package.json');
+    assert(app.config.keys.startsWith(pkg.name));
+
+    // const ctx = app.mockContext({});
+    // yield ctx.service.xx();
+  });
+
+  it('should GET /', () => {
+    return app.httpRequest()
+      .get('/')
+      .expect('hi, egg')
+      .expect(200);
+  });
+});