Browse Source

增加项目

guhongwei 3 years ago
commit
5fad99be1a

+ 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"
+}

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

@@ -0,0 +1,46 @@
+# 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:
+      - main
+      - master
+  pull_request:
+    branches:
+      - main
+      - 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 @@
+# server-user
+
+服务-用户管理
+
+## 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

+ 28 - 0
app.js

@@ -0,0 +1,28 @@
+'use strict';
+class AppBootHook {
+  constructor(app) {
+    this.app = app;
+  }
+
+  async willReady() {
+    const data = await this.app.model.Admin.findOne();
+    if (!data) {
+      // 没有管理员,初始化一个
+      const data = {
+        account: 'admin',
+        password: { secret: '123456' },
+      };
+      await this.app.model.Admin.create(data);
+    }
+  }
+
+  async serverDidReady() {
+    // 应用已经启动完毕
+    const ctx = await this.app.createAnonymousContext();
+    // 检查种子
+    // await ctx.service.install.index();
+    await ctx.service.util.rabbitMq.mission();
+  }
+
+}
+module.exports = AppBootHook;

+ 37 - 0
app/controller/.admin.js

@@ -0,0 +1,37 @@
+module.exports = {
+  create: {
+    requestBody: ['name', 'account', 'password'],
+  },
+  destroy: {
+    params: ['!id'],
+    service: 'delete',
+  },
+  update: {
+    params: ['!id'],
+    requestBody: ['name', 'account', 'password'],
+  },
+  show: {
+    parameters: {
+      params: ['!id'],
+    },
+    service: 'fetch',
+  },
+  index: {
+    parameters: {
+      query: {
+        'meta.createdAt@start': 'meta.createdAt@start',
+        'meta.createdAt@end': 'meta.createdAt@end',
+      },
+      // options: {
+      //   "meta.state": 0 // 默认条件
+      // },
+    },
+    service: 'query',
+    options: {
+      query: ['skip', 'limit'],
+      sort: ['meta.createdAt'],
+      desc: true,
+      count: true,
+    },
+  },
+};

+ 39 - 0
app/controller/.menu.js

@@ -0,0 +1,39 @@
+module.exports = {
+  create: {
+    requestBody: ['title', 'index', 'icon'],
+  },
+  destroy: {
+    params: ['!id'],
+    service: 'delete',
+  },
+  update: {
+    params: ['!id'],
+    requestBody: ['title', 'index', 'icon'],
+  },
+  show: {
+    parameters: {
+      params: ['!id'],
+    },
+    service: 'fetch',
+  },
+  index: {
+    parameters: {
+      query: {
+        title: 'title',
+        index: 'index',
+        'meta.createdAt@start': 'meta.createdAt@start',
+        'meta.createdAt@end': 'meta.createdAt@end',
+      },
+      // options: {
+      //   "meta.state": 0 // 默认条件
+      // },
+    },
+    service: 'query',
+    options: {
+      query: ['skip', 'limit'],
+      sort: ['meta.createdAt'],
+      desc: true,
+      count: true,
+    },
+  },
+};

+ 69 - 0
app/controller/.user.js

@@ -0,0 +1,69 @@
+module.exports = {
+  create: {
+    requestBody: [
+      "phone",
+      "password",
+      "type",
+      "icon",
+      "nickname",
+      "gender",
+      "work",
+      "status",
+    ],
+  },
+  destroy: {
+    params: ["!id"],
+    service: "delete",
+  },
+  update: {
+    params: ["!id"],
+    requestBody: [
+      "phone",
+      "password",
+      "type",
+      "icon",
+      "nickname",
+      "gender",
+      "work",
+      "status",
+    ],
+  },
+  show: {
+    parameters: {
+      params: ["!id"],
+    },
+    service: "fetch",
+  },
+  index: {
+    parameters: {
+      query: {
+        phone: "phone",
+        type: "type",
+        nickname: "nickname",
+        gender: "gender",
+        work: "work",
+        email: "email",
+        status: "status",
+        "meta.createdAt@start": "meta.createdAt@start",
+        "meta.createdAt@end": "meta.createdAt@end",
+      },
+      // options: {
+      //   "meta.state": 0 // 默认条件
+      // },
+    },
+    service: "query",
+    options: {
+      query: ["skip", "limit"],
+      sort: ["meta.createdAt"],
+      desc: true,
+      count: true,
+    },
+  },
+  login: {
+    requestBody: ["!phone", "!password"],
+  },
+  updatePwd: {
+    params: ['!id'],
+    requestBody: ['!password'],
+  },
+};

+ 13 - 0
app/controller/admin.js

@@ -0,0 +1,13 @@
+'use strict';
+const meta = require('./.admin.js');
+const Controller = require('egg').Controller;
+const { CrudController } = require('naf-framework-mongoose-free/lib/controller');
+
+// 
+class AdminController extends Controller {
+  constructor(ctx) {
+    super(ctx);
+    this.service = this.ctx.service.admin;
+  }
+}
+module.exports = CrudController(AdminController, meta);

+ 33 - 0
app/controller/home.js

@@ -0,0 +1,33 @@
+'use strict';
+const Controller = require('egg').Controller;
+const { CrudController } = require('naf-framework-mongoose-free/lib/controller');
+const { BusinessError, ErrorCode } = require('naf-core').Error;
+
+// 项目测试及管理员登陆
+class HomeController extends Controller {
+  async index() {
+    const { ctx } = this;
+    ctx.body = 'hi, egg';
+  }
+  /**
+   * 系统管理员登陆
+   * 太简单了,就不写service了,直接在这处理完完事了
+   */
+  async login() {
+    let admin = await this.ctx.model.Admin.findOne({}, '+password').exec();
+    if (!admin) throw new BusinessError(ErrorCode.FILE_FAULT, '未初始化管理员,拒绝请求!');
+    const { account, password } = this.ctx.request.body;
+    if (!account) throw new BusinessError(ErrorCode.BADPARAM, '未找到要登陆用户账号');
+    if (!password) throw new BusinessError(ErrorCode.BADPARAM, '未找到要登陆用户密码');
+    if (admin.account !== account) throw new BusinessError(ErrorCode.USER_NOT_EXIST, '未找到要登录的用户');
+    if (admin.password.secret !== password) throw new BusinessError(ErrorCode.BAD_PASSWORD, '密码错误');
+    admin = JSON.parse(JSON.stringify(admin));
+    delete admin.password;
+    delete admin.meta;
+    delete admin.__v;
+    delete admin._id;
+    const token = this.ctx.service.util.jwt.encrypt(admin);
+    this.ctx.ok({ data: token });
+  }
+}
+module.exports = CrudController(HomeController, {});

+ 13 - 0
app/controller/menu.js

@@ -0,0 +1,13 @@
+'use strict';
+const meta = require('./.menu.js');
+const Controller = require('egg').Controller;
+const { CrudController } = require('naf-framework-mongoose-free/lib/controller');
+
+// 菜单
+class MenuController extends Controller {
+  constructor(ctx) {
+    super(ctx);
+    this.service = this.ctx.service.menu;
+  }
+}
+module.exports = CrudController(MenuController, meta);

+ 13 - 0
app/controller/user.js

@@ -0,0 +1,13 @@
+'use strict';
+const meta = require('./.user.js');
+const Controller = require('egg').Controller;
+const { CrudController } = require('naf-framework-mongoose-free/lib/controller');
+
+// 用户管理
+class UserController extends Controller {
+  constructor(ctx) {
+    super(ctx);
+    this.service = this.ctx.service.user;
+  }
+}
+module.exports = CrudController(UserController, meta);

+ 53 - 0
app/middleware/request-log.js

@@ -0,0 +1,53 @@
+'use strict';
+module.exports = ({ toMongoDB = false }) =>
+  async function requestLog(ctx, next) {
+    await next();
+    try {
+      const request = ctx.request;
+      // 请求路由
+      const url = request.url;
+      // 请求方法
+      const method = request.method;
+      // get 请求不发日志
+      if (method === 'GET') return;
+      // 请求的分站标识
+      const tenant = ctx.tenant || 'master';
+      // 请求的用户
+      const user = ctx.user;
+      // 当前模块
+      const module = ctx.app.config.module;
+      // 所有的请求路由
+      const routers = ctx.router.stack;
+      // 匹配路由及http请求方法
+      const route = routers.find(route => {
+        const reg = new RegExp(route.regexp);
+        // 正则验证
+        const regResult = reg.test(url);
+        // http方法验证
+        const methodResult = route.methods.includes(method);
+        if (regResult && methodResult) return true;
+        return false;
+      });
+      if (!route) return;
+      // 不往数据库里写,就回去
+      if (!toMongoDB) return;
+      // 组织数据,给MQ,让日志服务去写
+      const { id: user_id, account, name } = user;
+      const logData = { user_id, account, name, _tenant: tenant, opera: route.name, path: url, module };
+      // 先用mq发送,不行再用http发
+      if (ctx.mq) {
+        ctx.service.util.rabbitMq.sendToMqQueue(logData, 'logs');
+      } else {
+        // http请求
+        const httpPrefix = ctx.app.config.httpPrefix;
+        if (httpPrefix && httpPrefix.logs) {
+          const uri = `${httpPrefix.logs}/logs`;
+          ctx.service.util.httpUtil.cpost(uri, logData);
+        }
+      }
+    } catch (error) {
+      // 没啥可输出,别中断就行
+    }
+
+
+  };

+ 19 - 0
app/model/admin.js

@@ -0,0 +1,19 @@
+'use strict';
+const Schema = require('mongoose').Schema;
+const metaPlugin = require('naf-framework-mongoose-free/lib/model/meta-plugin');
+const { Secret } = require('naf-framework-mongoose-free/lib/model/schema');
+// 系统管理员表
+const admin = {
+  name: { type: String, default: '系统管理员' }, // 显示名称
+  account: { type: String }, // 账号
+  password: { type: Secret, select: false }, // 密码
+  remark: { type: String },
+};
+const schema = new Schema(admin, { toJSON: { virtuals: true } });
+schema.index({ id: 1 });
+schema.index({ 'meta.createdAt': 1 });
+schema.plugin(metaPlugin);
+module.exports = app => {
+  const { mongoose } = app;
+  return mongoose.model('Admin', schema, 'admin');
+};

+ 20 - 0
app/model/menu.js

@@ -0,0 +1,20 @@
+'use strict';
+const Schema = require('mongoose').Schema;
+const moment = require('moment');
+const metaPlugin = require('naf-framework-mongoose-free/lib/model/meta-plugin');
+const { ObjectId } = require('mongoose').Types;
+// 菜单表
+const menu = {
+  title: { type: String }, // 菜单名称
+  index: { type: String }, // 路由
+  icon: { type: String }, // 图标
+  remark: { type: String },
+};
+const schema = new Schema(menu, { 'multi-tenancy': true, toJSON: { virtuals: true } });
+schema.index({ id: 1 });
+schema.index({ 'meta.createdAt': 1 });
+schema.plugin(metaPlugin);
+module.exports = app => {
+  const { mongoose } = app;
+  return mongoose.model('Menu', schema, 'menu');
+};

+ 32 - 0
app/model/user.js

@@ -0,0 +1,32 @@
+'use strict';
+const Schema = require('mongoose').Schema;
+const metaPlugin = require('naf-framework-mongoose-free/lib/model/meta-plugin');
+const { ObjectId } = require('mongoose').Types;
+const { Secret } = require('naf-framework-mongoose-free/lib/model/schema');
+// 用户表(分站模式)
+const user = {
+  phone: { type: String, required: false }, // 手机号
+  password: { type: Secret, select: false }, // 密码
+  type: { type: String, required: false }, // 用户类型
+  icon: { type: Array, required: false }, // 头像
+  nickname: { type: String, required: false }, // 昵称
+  gender: { type: String, required: false }, // 性别
+  work: { type: String, required: false }, // 岗位
+  email: { type: String, required: false }, // 邮箱
+  status: { type: String, required: false, default: '0' }, // 状态,0-待审,1:审核通过,2:审核拒绝
+  // account: { type: String, required: false }, // 账号
+  // uid: { type: String }, // 关联id,与各自业务有关的用户id
+  remark: { type: String },
+};
+const schema = new Schema(user, { 'multi-tenancy': true, toJSON: { virtuals: true } });
+schema.index({ id: 1 });
+schema.index({ phone: 1 });
+schema.index({ type: 1 });
+schema.index({ gender: 1 });
+schema.index({ status: 1 });
+schema.index({ 'meta.createdAt': 1 });
+schema.plugin(metaPlugin);
+module.exports = app => {
+  const { mongoose } = app;
+  return mongoose.model('User', schema, 'user');
+};

+ 13 - 0
app/router.js

@@ -0,0 +1,13 @@
+'use strict';
+
+/**
+ * @param {Egg.Application} app - egg application
+ */
+module.exports = app => {
+  const { router, controller } = app;
+  router.get('/', controller.home.index);
+  router.post('/courtAdmin/api/admin/login', controller.home.login);
+  router.get('/courtAdmin/api/useradmin', controller.admin.index);
+  require('./z_router/menu')(app); // 菜单
+  require('./z_router/user')(app); // 用户
+};

+ 15 - 0
app/service/admin.js

@@ -0,0 +1,15 @@
+'use strict';
+const { CrudService } = require('naf-framework-mongoose-free/lib/service');
+const { BusinessError, ErrorCode } = require('naf-core').Error;
+const _ = require('lodash');
+const assert = require('assert');
+
+// 管理员
+class AdminService extends CrudService {
+  constructor(ctx) {
+    super(ctx, 'admin');
+    this.model = this.ctx.model.Admin;
+  }
+}
+
+module.exports = AdminService;

+ 15 - 0
app/service/menu.js

@@ -0,0 +1,15 @@
+'use strict';
+const { CrudService } = require('naf-framework-mongoose-free/lib/service');
+const { BusinessError, ErrorCode } = require('naf-core').Error;
+const _ = require('lodash');
+const assert = require('assert');
+
+// 菜单
+class MenuService extends CrudService {
+  constructor(ctx) {
+    super(ctx, 'menu');
+    this.model = this.ctx.model.Menu;
+  }
+}
+
+module.exports = MenuService;

+ 42 - 0
app/service/user.js

@@ -0,0 +1,42 @@
+'use strict';
+const { CrudService } = require('naf-framework-mongoose-free/lib/service');
+const { BusinessError, ErrorCode } = require('naf-core').Error;
+const _ = require('lodash');
+const assert = require('assert');
+const crypto = require('crypto');
+const { ObjectId } = require('mongoose').Types;
+
+// 用户管理
+class UserService extends CrudService {
+  constructor(ctx) {
+    super(ctx, 'user');
+    this.model = this.ctx.model.User;
+  }
+  /**
+   * 登陆
+   * @param {Object} body 登陆参数
+   */
+  async login({ phone, password }) {
+    let user = await this.model.findOne({ phone }, '+password');
+    if (!user) throw new BusinessError(ErrorCode.USER_NOT_EXIST);
+    const { password: upwd, status } = user;
+    if (status !== '1') throw new BusinessError(ErrorCode.USER_NOT_BIND, '该账号处于禁止使用状态');
+    if (password !== upwd.secret) throw new BusinessError(ErrorCode.BAD_PASSWORD);
+    user = JSON.parse(JSON.stringify(user));
+    delete user.meta;
+    delete user.__v;
+    delete user.password;
+    // 用户信息toekn解密。小程序不适用
+    // const token = this.ctx.service.util.jwt.encrypt(user);
+    return user;
+  }
+  // 修改密码
+  async updatePwd({ id }, { password }) {
+    const data = await this.model.findById(id);
+    if (!data) throw new BusinessError(ErrorCode.USER_NOT_EXIST);
+    data.password = { secret: password };
+    await data.save();
+  }
+}
+
+module.exports = UserService;

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

@@ -0,0 +1,87 @@
+'use strict';
+const { AxiosService } = require('naf-framework-mongoose-free/lib/service');
+const { BusinessError, ErrorCode } = require('naf-core').Error;
+const { isNullOrUndefined } = require('naf-core').Util;
+const _ = require('lodash');
+
+//
+class HttpUtilService 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 cget(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 cpost(uri, data = {}, query, options) {
+    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;
+    }
+    const headers = { 'content-type': 'application/json' };
+    console.log(uri);
+    const url = this.merge(`${uri}`, options.params);
+    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.data;
+    }
+    const { status } = res;
+    console.warn(`[${uri}] fail: ${status}-${res.data.message} `);
+  }
+}
+
+module.exports = HttpUtilService;

+ 18 - 0
app/service/util/jwt.js

@@ -0,0 +1,18 @@
+'use strict';
+const { CrudService } = require('naf-framework-mongoose-free/lib/service');
+const jwt = require('jsonwebtoken');
+
+// jsonWebToken处理
+class JwtService extends CrudService {
+  constructor(ctx) {
+    super(ctx, 'jwt');
+  }
+
+  encrypt(data) {
+    const { secret } = this.config.jwt;
+    const token = jwt.sign(data, secret);
+    return token;
+  }
+}
+
+module.exports = JwtService;

+ 74 - 0
app/service/util/rabbitMq.js

@@ -0,0 +1,74 @@
+'use strict';
+
+const Service = require('egg').Service;
+const _ = require('lodash');
+
+class RabbitmqService extends Service {
+  // mission队列处理
+  async mission() {
+    const { mq } = this.ctx;
+    const { queue } = this.ctx.app.config;
+    if (mq && queue) {
+      const ch = await mq.conn.createChannel();
+      // const queue = 'freeAdmin/server-user';
+      try {
+        // 创建队列:在没有队列的情况,直接获取会导致程序无法启动
+        await ch.assertQueue(queue, { durable: false });
+        await ch.consume(queue, msg => this.dealMission(msg), { noAck: true });
+      } catch (error) {
+        this.ctx.logger.error('未找到订阅的队列');
+      }
+    } else {
+      this.ctx.logger.error('!!!!!!没有配置MQ插件!!!!!!');
+    }
+  }
+  // 执行任务
+  async dealMission(bdata) {
+    //   if (!bdata) this.ctx.logger.error('mission队列中信息不存在');
+    //   let data = bdata.content.toString();
+    //   try {
+    //     data = JSON.parse(data);
+    //   } catch (error) {
+    //     this.ctx.logger.error('数据不是object');
+    //   }
+    //   const { service, method, project, ...others } = data;
+    //   const arr = service.split('.');
+    //   let s = this.ctx.service;
+    //   for (const key of arr) {
+    //     s = s[key];
+    //   }
+    //   s[method](others);
+  }
+
+  /**
+   * 发送队列消息
+   * @param {Any} data 消息队列数据
+   * @param {String} queueKey 消息队列可以
+   */
+  async sendToMqQueue(data, queueKey) {
+    const { mq } = this.ctx;
+    const { sendQueue } = this.ctx.app.config;
+    let queue;
+    // 获取队列名称
+    if (_.isObject(sendQueue)) {
+      queue = sendQueue[queueKey];
+    }
+    if (mq && queue) {
+      if (!_.isString(data)) data = JSON.stringify(data);
+      const ch = await mq.conn.createChannel();
+      try {
+        // 创建队列:在没有队列的情况,直接获取会导致程序无法启动
+        // await ch.assertQueue(queue, { durable: false });
+        await ch.sendToQueue(queue, Buffer.from(data));
+        await ch.close();
+      } catch (error) {
+        console.error(error);
+        this.ctx.logger.error('mq消息发送失败');
+      }
+    } else {
+      this.ctx.logger.error('!!!!!!没有配置MQ插件!!!!!!');
+    }
+  }
+}
+
+module.exports = RabbitmqService;

+ 28 - 0
app/z_router/menu.js

@@ -0,0 +1,28 @@
+'use strict';
+// 路由配置
+const rkey = 'menu';
+const ckey = 'menu';
+const keyZh = '菜单';
+const routes = [
+  { method: 'get', path: `${rkey}`, controller: `${ckey}.index`, name: `${ckey}Query`, zh: `${keyZh}列表查询` },
+  { method: 'get', path: `${rkey}/:id`, controller: `${ckey}.show`, name: `${ckey}Show`, zh: `${keyZh}查询` },
+  { method: 'post', path: `${rkey}`, controller: `${ckey}.create`, middleware: [ 'password' ], name: `${ckey}Create`, zh: `创建${keyZh}` },
+  { method: 'post', path: `${rkey}/:id`, controller: `${ckey}.update`, name: `${ckey}Update`, zh: `修改${keyZh}` },
+  { method: 'delete', path: `${rkey}/:id`, controller: `${ckey}.destroy`, name: `${ckey}Delete`, zh: `删除${keyZh}` },
+];
+
+module.exports = app => {
+  const { router, config } = app;
+  const mwares = app.middleware;
+  for (const route of routes) {
+    const { method, path, controller: ctl, zh } = route;
+    let { middleware = [] } = route;
+    if (!method || !path || !ctl) continue;
+    // 拼全路径
+    const allPath = `${config.routePrefix}/${path}`;
+    // 处理中间件
+    if (middleware.length > 0) middleware = middleware.map(i => mwares[i]({ enable: true }));
+    // 注册路由
+    router[method](zh, allPath, ...middleware, ctl);
+  }
+};

+ 30 - 0
app/z_router/user.js

@@ -0,0 +1,30 @@
+'use strict';
+// 路由配置
+const rkey = 'user';
+const ckey = 'user';
+const keyZh = '用户';
+const routes = [
+  { method: 'post', path: `${rkey}/login`, controller: `${ckey}.login`, name: `${ckey}Login`, zh: `${keyZh}登陆` },
+  { method: 'post', path: `${rkey}/updatePwd/:id`, controller: `${ckey}.updatePwd`, name: `${ckey}UpdatePwd`, zh: `修改密码${keyZh}` },
+  { method: 'get', path: `${rkey}`, controller: `${ckey}.index`, name: `${ckey}Query`, zh: `${keyZh}列表查询` },
+  { method: 'get', path: `${rkey}/:id`, controller: `${ckey}.show`, name: `${ckey}Show`, zh: `${keyZh}查询` },
+  { method: 'post', path: `${rkey}`, controller: `${ckey}.create`, middleware: [ 'password' ], name: `${ckey}Create`, zh: `创建${keyZh}` },
+  { method: 'post', path: `${rkey}/:id`, controller: `${ckey}.update`, name: `${ckey}Update`, zh: `修改${keyZh}` },
+  { method: 'delete', path: `${rkey}/:id`, controller: `${ckey}.destroy`, name: `${ckey}Delete`, zh: `删除${keyZh}` },
+];
+
+module.exports = app => {
+  const { router, config } = app;
+  const mwares = app.middleware;
+  for (const route of routes) {
+    const { method, path, controller: ctl, zh } = route;
+    let { middleware = [] } = route;
+    if (!method || !path || !ctl) continue;
+    // 拼全路径
+    const allPath = `${config.routePrefix}/${path}`;
+    // 处理中间件
+    if (middleware.length > 0) middleware = middleware.map(i => mwares[i]({ enable: true }));
+    // 注册路由
+    router[method](zh, allPath, ...middleware, ctl);
+  }
+};

+ 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

+ 99 - 0
config/config.default.js

@@ -0,0 +1,99 @@
+/* eslint valid-jsdoc: "off" */
+
+'use strict';
+
+/**
+ * @param {Egg.EggAppInfo} appInfo app info
+ */
+const { jwt } = require('./config.secret');
+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 + '_1640765284662_2781';
+
+  // add your middleware config here
+  config.middleware = [ 'requestLog' ];
+
+  // add your user config here
+  const userConfig = {
+    // myAppName: 'egg',
+  };
+  // 日志
+  config.logger = {
+    level: 'DEBUG',
+    allowDebugAtProd: true,
+  };
+  // mq设置
+  // config.amqp = {
+  //   client: {
+  //     hostname: '127.0.0.1',
+  //     username: 'freeAdmin',
+  //     password: '1qaz2wsx',
+  //     vhost: 'freeAdmin',
+  //   },
+  //   app: true,
+  //   agent: true,
+  // };
+  // // 接收队列名称
+  // config.queue = 'freeAdmin/server-user';
+  // // 发送队列名称
+  // config.sendQueue = {
+  //   logs: 'freeAdmin/server-logs',
+  // };
+  // http请求前缀
+  config.httpPrefix = {
+    logs: 'http://localhost:13010/achieveAdmin/api',
+  };
+  // redis设置
+  // config.redis = {
+  //   client: {
+  //     port: 6379, // Redis port
+  //     host: '127.0.0.1', // Redis host
+  //     password: '123456',
+  //     db: 0,
+  //   },
+  // };
+  // 进程设置
+  config.cluster = {
+    listen: {
+      port: 13011,
+    },
+  };
+
+  // jwt设置
+  config.jwt = {
+    ...jwt,
+    expiresIn: '1d',
+    issuer: 'achieveAdmin',
+  };
+
+  // 数据库设置
+  config.dbName = 'achieveAdmin';
+  config.mongoose = {
+    url: `mongodb://localhost:27017/${config.dbName}`,
+    options: {
+      // user: 'admin',
+      // pass: 'admin',
+      // authSource: 'admin',
+      // useNewUrlParser: true,
+      // useCreateIndex: true,
+    },
+  };
+  // 路由设置
+  config.routePrefix = '/achieveAdmin/api';
+
+  // 中间件
+  config.requestLog = {
+    toMongoDB: true,
+  };
+  // config.module = 'user';
+  return {
+    ...config,
+    ...userConfig,
+  };
+};

+ 7 - 0
config/config.secret.js

@@ -0,0 +1,7 @@
+'use strict';
+
+module.exports = {
+  jwt: {
+    secret: 'Ziyouyanfa!@#',
+  },
+};

+ 15 - 0
config/plugin.js

@@ -0,0 +1,15 @@
+'use strict';
+// rabbitMq
+exports.amqp = {
+  enable: true,
+  package: 'egg-naf-amqp',
+};
+// redis
+exports.redis = {
+  enable: true,
+  package: 'egg-redis',
+};
+// 分站模式
+exports.multiTenancy = {
+  enable: true,
+};

+ 17 - 0
ecosystem.config.js

@@ -0,0 +1,17 @@
+'use strict';
+
+const app = 'server-achievekq';
+module.exports = {
+  apps: [{
+    name: app, // 应用名称
+    script: './server.js', // 实际启动脚本
+    out: `./logs/${app}.log`,
+    error: `./logs/${app}.err`,
+    watch: [ // 监控变化的目录,一旦变化,自动重启
+      'app', 'config',
+    ],
+    env: {
+      NODE_ENV: 'production', // 环境参数,当前指定为生产环境
+    },
+  }],
+};

+ 52 - 0
package.json

@@ -0,0 +1,52 @@
+{
+  "name": "server",
+  "version": "1.0.0",
+  "description": "服务-赛场",
+  "private": true,
+  "egg": {
+    "framework": "naf-framework-mongoose-free"
+  },
+  "dependencies": {
+    "egg": "^2.15.1",
+    "egg-naf-amqp": "0.0.13",
+    "egg-redis": "^2.4.0",
+    "egg-scripts": "^2.11.0",
+    "lodash": "^4.17.21",
+    "moment": "^2.29.1",
+    "naf-framework-mongoose-free": "^0.0.15"
+  },
+  "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",
+    "jsonwebtoken": "^8.5.1"
+  },
+  "engines": {
+    "node": ">=10.0.0"
+  },
+  "scripts": {
+    "start": "egg-scripts start --daemon --title=egg-server-server-user",
+    "stop": "egg-scripts stop --title=egg-server-server-user",
+    "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"
+}

+ 2 - 0
readme/admin.md

@@ -0,0 +1,2 @@
+# Admin 管理员相关
+### 没有设计成分站模式,为系统管理员,不管业务方面

+ 13 - 0
readme/user.md

@@ -0,0 +1,13 @@
+# User 相关
+### 设计为分站模式,目的是作为一个持续可使用的服务
+### 使用流程:
+
+|字段|类型|说明|
+|:-:|:-:|:-:|
+|account|String|账号|
+|password|Secret|密码|
+|uid|String|关联id,与各自业务有关的用户id|
+
+### 1. 创建: 各自业务创建账号时,走接口,在用户管理项目中可以保留任何信息,但是不能保留密码.目的是为了以最小的耦合性完成身份验证;
+### 2. 修改密码:用户登陆后,知道自己的分站,自己的id后可以过来修改密码
+### 3. 删除用户:要留底在各自的业务中留底,这边删除就是删除

+ 9 - 0
server.js

@@ -0,0 +1,9 @@
+
+// eslint-disable-next-line strict
+const egg = require('egg');
+
+const workers = Number(process.argv[2] || require('os').cpus().length);
+egg.startCluster({
+  workers,
+  baseDir: __dirname,
+});

+ 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);
+  });
+});