Quellcode durchsuchen

增加题库服务、试卷服务

asd123a20 vor 3 Jahren
Ursprung
Commit
bc88a768c9

+ 29 - 0
service-question-bank/.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
service-question-bank/.eslintignore

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

+ 3 - 0
service-question-bank/.eslintrc

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

+ 14 - 0
service-question-bank/.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
service-question-bank/.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
service-question-bank/README.md

@@ -0,0 +1,33 @@
+# service-code
+
+# 点赞/收藏/评论/留言
+
+## 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

+ 23 - 0
service-question-bank/app/controller/bank.js

@@ -0,0 +1,23 @@
+'use strict';
+const Controller = require('egg').Controller;
+
+class BankController extends Controller {
+  async create() {
+    const res = await this.ctx.service.bank.create(this.ctx.request.body);
+    this.ctx.body = res;
+  }
+  async update() {
+    const res = await this.ctx.service.bank.update(this.ctx.request.body);
+    this.ctx.body = res;
+  }
+  async delete() {
+    const res = await this.ctx.service.bank.delete(this.ctx.params);
+    this.ctx.body = res;
+  }
+  async query() {
+    const res = await this.ctx.service.bank.query(this.ctx.query);
+    this.ctx.body = res;
+  }
+}
+
+module.exports = BankController;

+ 27 - 0
service-question-bank/app/controller/paper.js

@@ -0,0 +1,27 @@
+'use strict';
+const Controller = require('egg').Controller;
+
+class PaperController extends Controller {
+  async create() {
+    const res = await this.ctx.service.paper.create(this.ctx.request.body);
+    this.ctx.body = res;
+  }
+  async update() {
+    const res = await this.ctx.service.paper.update(this.ctx.request.body);
+    this.ctx.body = res;
+  }
+  async delete() {
+    const res = await this.ctx.service.paper.delete(this.ctx.params);
+    this.ctx.body = res;
+  }
+  async query() {
+    const res = await this.ctx.service.paper.query(this.ctx.query);
+    this.ctx.body = res;
+  }
+  async setTopic() {
+    const res = await this.ctx.service.paper.setTopic(this.ctx.query);
+    this.ctx.body = res;
+  }
+}
+
+module.exports = PaperController;

+ 17 - 0
service-question-bank/app/model/bank.js

@@ -0,0 +1,17 @@
+'use strict';
+const Schema = require('mongoose').Schema;
+const SchemaDefine = {
+  // 标题
+  title: { type: String, required: true },
+  // 答案
+  answer: { type: String, required: true },
+  // 选项
+  options: { type: Array, required: true },
+  // 分数
+  fraction: { type: Number, required: true },
+};
+const schema = new Schema(SchemaDefine);
+module.exports = app => {
+  const { mongoose } = app;
+  return mongoose.model('bank', schema, 'bank');
+};

+ 17 - 0
service-question-bank/app/model/paper.js

@@ -0,0 +1,17 @@
+'use strict';
+const Schema = require('mongoose').Schema;
+const SchemaDefine = {
+  // 用户名
+  userName: { type: String, required: true },
+  // 用户ID
+  userId: { type: String, required: true },
+  // 试卷内容
+  list: { type: Array, required: true },
+  // 分数
+  fraction: { type: Number, required: true },
+};
+const schema = new Schema(SchemaDefine);
+module.exports = app => {
+  const { mongoose } = app;
+  return mongoose.model('paper', schema, 'paper');
+};

+ 19 - 0
service-question-bank/app/router.js

@@ -0,0 +1,19 @@
+'use strict';
+
+/**
+ * @param {Egg.Application} app - egg application
+ */
+module.exports = app => {
+  const { router, controller } = app;
+  // 题库
+  router.post('/api/question/bank/create', controller.bank.create);
+  router.post('/api/question/bank/update', controller.bank.update);
+  router.delete('/api/question/bank/delete/:id', controller.bank.delete);
+  router.get('/api/question/bank/query', controller.bank.query);
+  // 试卷
+  router.post('/api/question/paper/create', controller.paper.create);
+  router.post('/api/question/paper/update', controller.paper.update);
+  router.delete('/api/question/paper/delete/:id', controller.paper.delete);
+  router.get('/api/question/paper/query', controller.paper.query);
+  router.get('/api/question/paper/setTopic', controller.paper.setTopic);
+};

+ 68 - 0
service-question-bank/app/service/bank.js

@@ -0,0 +1,68 @@
+'use strict';
+
+const assert = require('assert');
+const Service = require('egg').Service;
+class BankService extends Service {
+  constructor(ctx) {
+    super(ctx);
+    this.model = this.ctx.model.Bank;
+  }
+  async create({ title, answer, options, fraction }) {
+    assert(title, '标题不存在');
+    assert(answer, '答案不存在');
+    assert(options, '选项不存在');
+    try {
+      const total = await this.model.find({ title });
+      if (total.length > 0) {
+        return { errcode: -1001, errmsg: '问题不能重复添加' };
+      }
+      const res = await this.model.create({ title, answer, options, fraction });
+      return { errcode: 0, errmsg: 'ok', data: res };
+    } catch (error) {
+      throw error;
+    }
+  }
+  async update({ id, title, answer, options, fraction }) {
+    assert(id, 'id不存在');
+    try {
+      await this.model.updateOne({ _id: id }, { title, answer, options, fraction });
+      return { errcode: 0, errmsg: 'ok', data: '' };
+    } catch (error) {
+      throw error;
+    }
+  }
+  async delete({ id }) {
+    assert(id, 'id不存在');
+    try {
+      await this.model.deleteOne({ _id: id });
+      return { errcode: 0, errmsg: 'ok', data: '' };
+    } catch (error) {
+      throw error;
+    }
+  }
+  async query({ skip, limit, title }) {
+    const filter = {};
+    const arr = { title };
+    for (const e in arr) {
+      const data = `{ "${e}": { "$regex": "${arr[e]}" } }`;
+      if (arr[e]) {
+        filter.$or = [];
+        filter.$or.push(JSON.parse(data));
+      }
+    }
+    try {
+      const total = await this.model.find({ ...filter });
+      let res;
+      if (skip && limit) {
+        res = await this.model.find({ ...filter }).skip(Number(skip) * Number(limit)).limit(Number(limit));
+      } else {
+        res = await this.model.find({ ...filter });
+      }
+      return { errcode: 0, errmsg: 'ok', data: res, total: total.length };
+    } catch (error) {
+      throw error;
+    }
+  }
+}
+
+module.exports = BankService;

+ 95 - 0
service-question-bank/app/service/paper.js

@@ -0,0 +1,95 @@
+'use strict';
+
+const assert = require('assert');
+const Service = require('egg').Service;
+class PaperService extends Service {
+  constructor(ctx) {
+    super(ctx);
+    this.model = this.ctx.model.Paper;
+    this.bankModel = this.ctx.model.bank;
+  }
+  async create({ userName, userId, list }) {
+    assert(userName, '用户名不存在');
+    assert(userId, '用户ID不存在');
+    assert(list, '内容不存在');
+    try {
+      let fraction = 0;
+      await list.filter(async e => {
+        const data = await this.bankModel.find({ title: e.title });
+        if (data.answer === e.answer) fraction += data.answer;
+      });
+      await this.model.create({ userName, userId, list, fraction });
+      return { errcode: 0, errmsg: 'ok', data: { fraction } };
+    } catch (error) {
+      throw error;
+    }
+  }
+  async update({ id, userName, userId, list, fraction }) {
+    assert(id, 'id不存在');
+    try {
+      await this.model.updateOne({ _id: id }, { userName, userId, list, fraction });
+      return { errcode: 0, errmsg: 'ok', data: '' };
+    } catch (error) {
+      throw error;
+    }
+  }
+  async delete({ id }) {
+    assert(id, 'id不存在');
+    try {
+      await this.model.deleteOne({ _id: id });
+      return { errcode: 0, errmsg: 'ok', data: '' };
+    } catch (error) {
+      throw error;
+    }
+  }
+  async query({ skip, limit, userName, fraction }) {
+    const filter = {};
+    const arr = { userName, fraction };
+    for (const e in arr) {
+      const data = `{ "${e}": { "$regex": "${arr[e]}" } }`;
+      if (arr[e]) {
+        filter.$or = [];
+        filter.$or.push(JSON.parse(data));
+      }
+    }
+    try {
+      const total = await this.model.find({ ...filter });
+      let res;
+      if (skip && limit) {
+        res = await this.model.find({ ...filter }).skip(Number(skip) * Number(limit)).limit(Number(limit));
+      } else {
+        res = await this.model.find({ ...filter });
+      }
+      return { errcode: 0, errmsg: 'ok', data: res, total: total.length };
+    } catch (error) {
+      throw error;
+    }
+  }
+  async setTopic({ isRandom, total }) {
+    try {
+      let data;
+      const list = [];
+      if (!isRandom) {
+        // 不随机
+        data = await this.bankModel.find({}, { answer: false }).skip(0).limit(Number(total));
+      } else {
+        // 随机
+        const totals = await this.bankModel.find();
+        const arr = [];
+        for (let i = 0; i < total; i++) {
+          const num = Math.floor(Math.random() * totals.length);
+          if (!arr.includes(num)) {
+            arr.push(num);
+            const res = await this.bankModel.find({}, { answer: false }).skip(Number(num)).limit(1);
+            list.push(...res);
+          }
+        }
+      }
+      return { errcode: 0, errmsg: 'ok', data: !isRandom ? data : list, total };
+    } catch (error) {
+      throw error;
+    }
+  }
+}
+
+module.exports = PaperService;

+ 14 - 0
service-question-bank/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

+ 54 - 0
service-question-bank/config/config.default.js

@@ -0,0 +1,54 @@
+/* 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 + '_1635902541751_9477';
+
+  // add your middleware config here
+  config.middleware = [];
+  // add your user config here
+  const userConfig = {
+    // myAppName: 'egg',
+  };
+  // 安全配置
+  config.security = {
+    csrf: {
+      // ignoreJSON: true, // 默认为 false,当设置为 true 时,将会放过所有 content-type 为 `application/json` 的请求
+      enable: false,
+    },
+  };
+  config.cluster = {
+    listen: {
+      port: 7001,
+    },
+  };
+  // 数据库配置
+  config.mongoose = {
+    url: 'mongodb://127.0.0.1/Microservices',
+    options: {
+      // user: 'root',
+      // pass: 'cms@cc-lotus',
+      // authSource: 'admin',
+      // useNewUrlParser: true,
+      // useCreateIndex: true,
+    },
+  };
+  config.logger = {
+    level: 'DEBUG',
+  };
+  return {
+    ...config,
+    ...userConfig,
+  };
+};

+ 9 - 0
service-question-bank/config/plugin.js

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

+ 17 - 0
service-question-bank/ecosystem.config.js

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

+ 5 - 0
service-question-bank/jsconfig.json

@@ -0,0 +1,5 @@
+{
+  "include": [
+    "**/*"
+  ]
+}

+ 47 - 0
service-question-bank/package.json

@@ -0,0 +1,47 @@
+{
+  "name": "service-reader",
+  "version": "1.0.0",
+  "description": "",
+  "private": true,
+  "egg": {
+    "declarations": true
+  },
+  "dependencies": {
+    "egg": "^2.15.1",
+    "egg-mongoose": "^3.3.1",
+    "egg-scripts": "^2.11.0"
+  },
+  "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-service-reader",
+    "stop": "egg-scripts stop --title=egg-server-service-reader",
+    "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": "",
+  "license": "MIT"
+}

+ 9 - 0
service-question-bank/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
service-question-bank/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);
+  });
+});