lrf402788946 4 年之前
当前提交
75461a7327

+ 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 @@
+# service-article
+
+
+
+## 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

+ 59 - 0
app/controller/.refute.js

@@ -0,0 +1,59 @@
+module.exports = {
+  create: {
+    requestBody: [
+      "user_id",
+      "title",
+      "origin",
+      "renew_time",
+      "content",
+      "website",
+      "fileUrl",
+      "imgUrl",
+      "remark",
+    ],
+  },
+  destroy: {
+    params: ["!id"],
+    service: "delete",
+  },
+  update: {
+    params: ["!id"],
+    requestBody: [
+      "user_id",
+      "title",
+      "origin",
+      "renew_time",
+      "content",
+      "website",
+      "fileUrl",
+      "imgUrl",
+      "remark",
+    ],
+  },
+  show: {
+    parameters: {
+      params: ["!id"],
+    },
+    service: "fetch",
+  },
+  index: {
+    parameters: {
+      query: {
+        title: "%title%",
+        origin: "%origin%",
+        "create_time@start": "create_time@start",
+        "create_time@end": "create_time@end",
+      },
+      // options: {
+      //   "meta.state": 0 // 默认条件
+      // },
+    },
+    service: "query",
+    options: {
+      query: ["skip", "limit"],
+      sort: ["meta.createdAt"],
+      desc: true,
+      count: true,
+    },
+  },
+};

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

+ 13 - 0
app/controller/refute.js

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

+ 22 - 0
app/middleware/read.js

@@ -0,0 +1,22 @@
+'use strict';
+const _ = require('lodash');
+const { ObjectId } = require('mongoose').Types;
+module.exports = options => {
+  return async function read(ctx, next) {
+    // 获取url
+    const uri = ctx.request.url;
+    // 以 / 将字符串分段成为数组
+    const arr = uri.split('/');
+    // fetch的格式是最后的'/'后的内容为ObjectId
+    const tail = _.last(arr);
+    // 使用mongoose的 ObjectId类 去校验是否为ObjectId,不是ObjectId的情况,则不能直接使用plus,plus中使用的是findById
+    const res = ObjectId.isValid(tail);
+    if (res) {
+      // service.read.plus对该数据的read+1
+      await ctx.service.read.plus(options, tail);
+    }
+    // 别忘了最后要正常继续工作
+    await next();
+  };
+
+};

+ 29 - 0
app/model/refute.js

@@ -0,0 +1,29 @@
+'use strict';
+const Schema = require('mongoose').Schema;
+const moment = require('moment');
+const metaPlugin = require('naf-framework-mongoose/lib/model/meta-plugin');
+const { ObjectId } = require('mongoose').Types;
+// 文字/辟谣表
+const refute = {
+  user_id: { type: ObjectId },
+  title: { type: String }, // 标题
+  origin: { type: String }, // 来源
+  renew_time: { type: String }, // 更新时间
+  content: { type: String }, // 内容
+  website: { type: String }, // 文字网址
+  fileUrl: { type: String }, // 文章视频
+  imgUrl: { type: String }, // 图片
+  read: { type: Number, default: 0 }, // 阅读数
+  remark: { type: String, maxLength: 200 },
+  create_time: { type: String, default: moment(new Date()).format('YYYY-MM-DD HH:mm:ss') },
+};
+const schema = new Schema(refute, { toJSON: { virtuals: true } });
+schema.index({ id: 1 });
+schema.index({ title: 1 });
+schema.index({ origin: 1 });
+schema.index({ 'meta.createdAt': 1 });
+schema.plugin(metaPlugin);
+module.exports = app => {
+  const { mongoose } = app;
+  return mongoose.model('Refute', schema, 'refute');
+};

+ 11 - 0
app/router.js

@@ -0,0 +1,11 @@
+'use strict';
+
+/**
+ * @param {Egg.Application} app - egg application
+ */
+module.exports = app => {
+  const { router, controller } = app;
+  const profix = '/api/article/';
+  router.get('/', controller.home.index);
+  require('./router/refute')(app); // 文章/辟谣
+};

+ 12 - 0
app/router/refute.js

@@ -0,0 +1,12 @@
+'use strict';
+
+
+module.exports = app => {
+  const { router, controller } = app;
+  const profix = '/api/article/';
+  const target = 'refute';
+  const readMiddleware = app.middleware.read(target);
+  router.get(target, `${profix}${target}/:id`, readMiddleware, controller[target].show);
+  router.resources(target, `${profix}${target}`, controller[target]); // index、create、show、destroy
+  router.post(target, `${profix}${target}/update/:id`, controller[target].update);
+};

+ 23 - 0
app/service/read.js

@@ -0,0 +1,23 @@
+'use strict';
+const { CrudService } = require('naf-framework-mongoose/lib/service');
+const { BusinessError, ErrorCode } = require('naf-core').Error;
+const _ = require('lodash');
+const assert = require('assert');
+
+// 阅读数加一
+class ReadService extends CrudService {
+  constructor(ctx) {
+    super(ctx, 'read');
+  }
+  async plus(model, id) {
+    assert(model && id, '缺少数据');
+    // _.capitalize=>首字母大写
+    const data = await this.ctx.model[_.capitalize(model)].findById(id);
+    if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到要阅读的数据');
+    // 默认将read给0,别引起错误,数据不对可以讨论,找原因,但是程序中断了就不好了
+    data.read = (data.read || 0) + 1;
+    await data.save();
+  }
+}
+
+module.exports = ReadService;

+ 15 - 0
app/service/refute.js

@@ -0,0 +1,15 @@
+'use strict';
+const { CrudService } = require('naf-framework-mongoose/lib/service');
+const { BusinessError, ErrorCode } = require('naf-core').Error;
+const _ = require('lodash');
+const assert = require('assert');
+
+// 文字/辟谣
+class RefuteService extends CrudService {
+  constructor(ctx) {
+    super(ctx, 'refute');
+    this.model = this.ctx.model.Refute;
+  }
+}
+
+module.exports = RefuteService;

+ 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

+ 65 - 0
config/config.default.js

@@ -0,0 +1,65 @@
+/* eslint valid-jsdoc: "off" */
+
+'use strict';
+const { jwt } = require('./config.secret');
+
+/**
+ * @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 + '_1616739379301_3896';
+
+  // add your middleware config here
+  config.middleware = [];
+
+  // add your user config here
+  const userConfig = {
+    // myAppName: 'egg',
+  };
+
+  // mongoose config
+  config.mongoose = {
+    url: 'mongodb://127.0.0.1:27017/article',
+    options: {
+      // user: 'admin',
+      // pass: 'admin',
+      // authSource: 'admin',
+      // useNewUrlParser: true,
+      // useCreateIndex: true,
+    },
+  };
+
+  // 安全配置
+  config.security = {
+    csrf: {
+      // ignoreJSON: true, // 默认为 false,当设置为 true 时,将会放过所有 content-type 为 `application/json` 的请求
+      enable: false,
+    },
+  };
+
+  // JWT config
+  config.jwt = {
+    ...jwt,
+    expiresIn: '1d',
+    issuer: 'article',
+  };
+
+  // add your config here
+  config.cluster = {
+    listen: {
+      port: 10010,
+    },
+  };
+
+  return {
+    ...config,
+    ...userConfig,
+  };
+};

+ 7 - 0
config/config.secret.js

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

+ 9 - 0
config/plugin.js

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

+ 50 - 0
package.json

@@ -0,0 +1,50 @@
+{
+  "name": "service-article",
+  "version": "1.0.0",
+  "description": "",
+  "private": true,
+  "egg": {
+    "framework": "naf-framework-mongoose"
+  },
+  "dependencies": {
+    "egg": "^2.15.1",
+    "egg-scripts": "^2.11.0",
+    "jsonwebtoken": "^8.5.1",
+    "lodash": "^4.17.15",
+    "moment": "^2.29.1",
+    "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-service-article",
+    "stop": "egg-scripts stop --title=egg-server-service-article",
+    "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);
+  });
+});