lrf преди 3 години
ревизия
09db1af245

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

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

+ 33 - 0
README.md

@@ -0,0 +1,33 @@
+# db-init-server
+
+快速制作数据库表
+
+## 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

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

@@ -0,0 +1,39 @@
+module.exports = {
+  create: {
+    requestBody: ['!name', 'desc', 'remark'],
+  },
+  destroy: {
+    params: ['!id'],
+    service: 'delete',
+  },
+  update: {
+    params: ['!id'],
+    requestBody: ['!name', 'desc', 'remark'],
+  },
+  show: {
+    parameters: {
+      params: ['!id'],
+    },
+    service: 'fetch',
+  },
+  index: {
+    parameters: {
+      query: {
+        name: '%name%',
+        project: 'project',
+        '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/.table.js

@@ -0,0 +1,39 @@
+module.exports = {
+  create: {
+    requestBody: ['!name', '!project', 'columns', 'remark'],
+  },
+  destroy: {
+    params: ['!id'],
+    service: 'delete',
+  },
+  update: {
+    params: ['!id'],
+    requestBody: ['!name', '!project', 'columns', 'remark'],
+  },
+  show: {
+    parameters: {
+      params: ['!id'],
+    },
+    service: 'fetch',
+  },
+  index: {
+    parameters: {
+      query: {
+        name: '%name%',
+        project: '%project%',
+        '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,
+    },
+  },
+};

+ 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 = '<p style="color:blue">hi, egg</p>';
+  }
+}
+
+module.exports = HomeController;

+ 14 - 0
app/controller/options.js

@@ -0,0 +1,14 @@
+'use strict';
+const Controller = require('egg').Controller;
+const { CrudController } = require('naf-framework-mongoose-free/lib/controller');
+const options = require('../public/options');
+const _ = require('lodash');
+// 选项
+class OptionsController extends Controller {
+  async index() {
+    const body = this.ctx.request.body;
+    const data = _.pick(options, body);
+    this.ctx.ok({ data });
+  }
+}
+module.exports = CrudController(OptionsController, {});

+ 13 - 0
app/controller/project.js

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

+ 12 - 0
app/controller/table.js

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

+ 18 - 0
app/model/project.js

@@ -0,0 +1,18 @@
+'use strict';
+const Schema = require('mongoose').Schema;
+const metaPlugin = require('naf-framework-mongoose-free/lib/model/meta-plugin');
+// 项目表
+const project = {
+  name: { type: String, required: true }, // 项目名称
+  desc: { type: String }, // 描述
+  remark: { type: String },
+};
+const schema = new Schema(project, { toJSON: { virtuals: true } });
+schema.index({ id: 1 });
+schema.index({ name: 1 });
+schema.index({ 'meta.createdAt': 1 });
+schema.plugin(metaPlugin);
+module.exports = app => {
+  const { mongoose } = app;
+  return mongoose.model('Project', schema, 'project');
+};

+ 35 - 0
app/model/table.js

@@ -0,0 +1,35 @@
+'use strict';
+const Schema = require('mongoose').Schema;
+const metaPlugin = require('naf-framework-mongoose-free/lib/model/meta-plugin');
+const { ObjectId } = require('mongoose').Types;
+
+const column = new Schema(
+  {
+    title: { type: String, required: true }, // 字段名,必须是英文
+    type: { type: String, default: String }, // 字段类型,默认:String
+    required: { type: Boolean, default: false }, // 是否必填,默认:否
+    maxLength: { type: Number }, // 最大长度限制
+    remark: { type: String },
+  },
+  {
+    _id: false,
+  }
+);
+
+// 字段表
+const table = {
+  name: { type: String, required: true },
+  project: { type: ObjectId, required: true }, // 项目
+  columns: [ column ], // 字段列表
+  remark: { type: String },
+};
+const schema = new Schema(table, { toJSON: { virtuals: true } });
+schema.index({ id: 1 });
+schema.index({ name: 1 });
+schema.index({ project: 1 });
+schema.index({ 'meta.createdAt': 1 });
+schema.plugin(metaPlugin);
+module.exports = app => {
+  const { mongoose } = app;
+  return mongoose.model('Table', schema, 'table');
+};

+ 27 - 0
app/public/options.js

@@ -0,0 +1,27 @@
+'use strict';
+module.exports = {
+  columnType: [
+    {
+      label: '字符串',
+      value: 'String',
+    },
+    {
+      label: '数字',
+      value: 'Number',
+    },
+    {
+      label: 'ObjectId',
+      value: 'ObjectId',
+    },
+  ],
+  required: [
+    {
+      label: '必填',
+      value: true,
+    },
+    {
+      label: '非必填',
+      value: false,
+    },
+  ],
+};

+ 13 - 0
app/router.js

@@ -0,0 +1,13 @@
+'use strict';
+
+/**
+ * @param {Egg.Application} app - egg application
+ */
+module.exports = app => {
+  const { router, controller, config } = app;
+  const prefix = config.routePrefix;
+  router.get(`${prefix}`, controller.home.index);
+  router.post(`${prefix}/options`, controller.options.index);
+  require('./z_router/project')(app); // 项目
+  require('./z_router/table')(app); // 表
+};

+ 13 - 0
app/service/project.js

@@ -0,0 +1,13 @@
+'use strict';
+const { CrudService } = require('naf-framework-mongoose-free/lib/service');
+const { BusinessError, ErrorCode } = require('naf-core').Error;
+
+// 项目
+class ProjectService extends CrudService {
+  constructor(ctx) {
+    super(ctx, 'project');
+    this.model = this.ctx.model.Project;
+  }
+}
+
+module.exports = ProjectService;

+ 23 - 0
app/service/table.js

@@ -0,0 +1,23 @@
+'use strict';
+const { CrudService } = require('naf-framework-mongoose-free/lib/service');
+
+class TableService extends CrudService {
+  constructor(ctx) {
+    super(ctx, 'table');
+    this.model = this.ctx.model.Table;
+  }
+
+  async query(condition) {
+    condition = this.turnFilter(this.turnDateRangeQuery(condition));
+    console.log(condition);
+    const res = await this.model.find(condition);
+    console.log(res);
+  }
+
+  async count(condition) {
+    console.log(condition);
+
+  }
+}
+
+module.exports = TableService;

+ 9 - 0
app/z_router/project.js

@@ -0,0 +1,9 @@
+'use strict';
+
+module.exports = app => {
+  const { router, controller, config } = app;
+  const target = 'project';
+  const prefix = config.routePrefix;
+  router.resources(target, `${prefix}/${target}`, controller[target]); // index、create、show、destroy
+  router.post(target, `${prefix}/${target}/:id`, controller[target].update);
+};

+ 9 - 0
app/z_router/table.js

@@ -0,0 +1,9 @@
+'use strict';
+
+module.exports = app => {
+  const { router, controller, config } = app;
+  const target = 'table';
+  const prefix = config.routePrefix;
+  router.resources(target, `${prefix}/${target}`, controller[target]); // index、create、show、destroy
+  router.post(target, `${prefix}/${target}/:id`, controller[target].update);
+};

+ 50 - 0
config/config.default.js

@@ -0,0 +1,50 @@
+/* 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 + '_1635992838175_1417';
+
+  // add your middleware config here
+  config.middleware = [];
+
+  // add your user config here
+  const userConfig = {
+    // myAppName: 'egg',
+  };
+
+  config.routePrefix = '/api/util/dbInit';
+
+  config.cluster = {
+    listen: {
+      port: 6900,
+    },
+  };
+
+  config.dbName = 'dbInit';
+  config.mongoose = {
+    url: `mongodb://localhost:27017/${config.dbName}`,
+    options: {
+      // user: 'admin',
+      // pass: 'admin',
+      // authSource: 'admin',
+      useNewUrlParser: true,
+      useCreateIndex: true,
+    },
+  };
+
+  return {
+    ...config,
+    ...userConfig,
+  };
+};

+ 22 - 0
config/config.prod.js

@@ -0,0 +1,22 @@
+'use strict';
+
+module.exports = () => {
+  const config = exports = {};
+
+  config.logger = {
+    level: 'INFO',
+    consoleLevel: 'INFO',
+  };
+  config.dbName = 'dbInit';
+  config.mongoose = {
+    url: `mongodb://localhost:27017/${config.dbName}`,
+    options: {
+      user: 'admin',
+      pass: 'admin',
+      authSource: 'admin',
+      useNewUrlParser: true,
+      useCreateIndex: true,
+    },
+  };
+  return config;
+};

+ 9 - 0
config/plugin.js

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

+ 17 - 0
ecosystem.config.js

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

+ 49 - 0
package.json

@@ -0,0 +1,49 @@
+{
+  "name": "db-init-server",
+  "version": "1.0.0",
+  "description": "快速制作数据库表",
+  "private": true,
+  "egg": {
+    "framework": "naf-framework-mongoose-free"
+  },
+  "dependencies": {
+    "egg": "^2.15.1",
+    "egg-scripts": "^2.11.0",
+    "lodash": "^4.17.21",
+    "moment": "^2.29.1",
+    "naf-framework-mongoose-free": "^0.0.2"
+  },
+  "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-db-init-server",
+    "stop": "egg-scripts stop --title=egg-server-db-init-server",
+    "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"
+}

+ 9 - 0
server.js

@@ -0,0 +1,9 @@
+
+// eslint-disable-next-line strict
+const egg = require('egg');
+
+const workers = Number(1);
+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);
+  });
+});