guhongwei 2 rokov pred
rodič
commit
6f0f2af6f5

+ 10 - 2
src/config/config.default.ts

@@ -1,9 +1,17 @@
 import { MidwayConfig } from '@midwayjs/core';
 
 export default {
-  // use for cookie sign key, should change to your own and keep security
   keys: '1679015772536_8873',
   koa: {
-    port: 7001,
+    port: 10111,
   },
+  jwt: {
+    secret: 'Ziyouyanfa!@#',
+    expiresIn: '2d',
+  },
+  redis_timeout: 300, //s
+  axios: {
+    clients: {},
+  },
+
 } as MidwayConfig;

+ 37 - 0
src/config/config.local.ts

@@ -0,0 +1,37 @@
+import { MidwayConfig } from '@midwayjs/core';
+const ip = '127.0.0.1';
+const project = 'testproject';
+export default {
+  keys: '1672292154640_555',
+  koa: {
+    globalPrefix: `/${project}/v1/api`,
+  },
+  swagger: {
+    swaggerPath: `/dev/${project}/v1/api/doc`,
+  },
+  mongoose: {
+    dataSource: {
+      default: {
+        uri: `mongodb://${ip}:27017/${project}`,
+        options: {
+          user: 'admin',
+          pass: 'admin',
+          authSource: 'admin',
+          useNewUrlParser: true,
+        },
+        entities: ['./entity'],
+      },
+    },
+  },
+  redis: {
+    // client: {
+    //   port: 6379, // Redis port
+    //   host: ip, // Redis host
+    //   password: '123456',
+    //   db: 3,
+    // },
+  },
+  axios: {
+    clients: {},
+  },
+} as MidwayConfig;

+ 37 - 0
src/config/config.prod.ts

@@ -0,0 +1,37 @@
+import { MidwayConfig } from '@midwayjs/core';
+const ip = '127.0.0.1';
+const project = 'testproject';
+export default {
+  keys: '1672292154640_555',
+  koa: {
+    globalPrefix: `/${project}/v1/api`,
+  },
+  swagger: {
+    swaggerPath: `/${project}/v1/api/doc`,
+  },
+  mongoose: {
+    dataSource: {
+      default: {
+        uri: `mongodb://${ip}:27017/${project}`,
+        options: {
+          user: 'admin',
+          pass: 'admin',
+          authSource: 'admin',
+          useNewUrlParser: true,
+        },
+        entities: ['./entity'],
+      },
+    },
+  },
+  redis: {
+    // client: {
+    //   port: 6379, // Redis port
+    //   host: ip, // Redis host
+    //   password: '123456',
+    //   db: 4,
+    // },
+  },
+  axios: {
+    clients: {},
+  },
+} as MidwayConfig;

+ 26 - 7
src/configuration.ts

@@ -2,15 +2,36 @@ import { Configuration, App } from '@midwayjs/core';
 import * as koa from '@midwayjs/koa';
 import * as validate from '@midwayjs/validate';
 import * as info from '@midwayjs/info';
+import * as swagger from '@midwayjs/swagger';
+import * as jwt from '@midwayjs/jwt';
+import * as redis from '@midwayjs/redis';
+import * as axios from '@midwayjs/axios';
+// import { IMidwayContainer } from '@midwayjs/core';
 import { join } from 'path';
-// import { DefaultErrorFilter } from './filter/default.filter';
-// import { NotFoundFilter } from './filter/notfound.filter';
+// freemidway组件项目
+import * as FreeFrame from 'free-midway-component';
+// import { FrameworkErrorEnum, ServiceError } from 'free-midway-component';
+// 控制器执行前函数
 import { ReportMiddleware } from './middleware/report.middleware';
-
+// 请求成功,失败提示
+// const axiosResponse = response => {
+//   if (response.status === 200) return response.data;
+//   else {
+//     console.log(JSON.stringify(response));
+//     throw new ServiceError('请求失败', FrameworkErrorEnum.SERVICE_FAULT);
+//   }
+// };
+// const axiosError = error => {
+//   return Promise.reject(error);
+// };
 @Configuration({
   imports: [
-    koa,
+    FreeFrame,
     validate,
+    jwt,
+    redis,
+    axios,
+    swagger,
     {
       component: info,
       enabledEnvironment: ['local'],
@@ -23,9 +44,7 @@ export class ContainerLifeCycle {
   app: koa.Application;
 
   async onReady() {
-    // add middleware
     this.app.useMiddleware([ReportMiddleware]);
-    // add filter
-    // this.app.useFilter([NotFoundFilter, DefaultErrorFilter]);
+    // this.app.getMiddleware().insertFirst(ReportMiddleware);
   }
 }

+ 0 - 18
src/controller/api.controller.ts

@@ -1,18 +0,0 @@
-import { Inject, Controller, Get, Query } from '@midwayjs/core';
-import { Context } from '@midwayjs/koa';
-import { UserService } from '../service/user.service';
-
-@Controller('/api')
-export class APIController {
-  @Inject()
-  ctx: Context;
-
-  @Inject()
-  userService: UserService;
-
-  @Get('/get_user')
-  async getUser(@Query('uid') uid) {
-    const user = await this.userService.getUser({ uid });
-    return { success: true, message: 'OK', data: user };
-  }
-}

+ 1 - 1
src/controller/home.controller.ts

@@ -1,9 +1,9 @@
 import { Controller, Get } from '@midwayjs/core';
-
 @Controller('/')
 export class HomeController {
   @Get('/')
   async home(): Promise<string> {
     return 'Hello Midwayjs!';
   }
+  // @Inject()
 }

+ 63 - 0
src/controller/test.controller.ts

@@ -0,0 +1,63 @@
+import { Body, Controller, Del, Get, Inject, Param, Post, Query } from '@midwayjs/decorator';
+import { ApiQuery, ApiResponse, ApiTags } from '@midwayjs/swagger';
+import { Validate } from '@midwayjs/validate';
+import { BaseController } from 'free-midway-component';
+import { TestService } from '../service/test.service';
+import { CreateDTO_test, CreateVO_test, FetchVO_test, QueryDTO_test, QueryVO_test, UpdateDTO_test, UpdateVO_test } from '../interface/test.interface';
+
+@ApiTags(['测试表索引'])
+@Controller('/test')
+export class TestController extends BaseController {
+  @Inject()
+  service: TestService;
+
+  @Post('/')
+  @Validate()
+  @ApiResponse({ type: CreateVO_test })
+  async create(@Body() data: CreateDTO_test) {
+    const result = await this.service.create(data);
+    return result;
+  }
+  @Get('/')
+  @ApiQuery({ name: 'query' })
+  @ApiResponse({ type: QueryVO_test })
+  async query(@Query() filter: QueryDTO_test, @Query('skip') skip: number, @Query('limit') limit: number) {
+    const data = await this.service.query(filter, { skip, limit, sort: { 'meta.createdAt': -1 } });
+    const total = await this.service.count(filter);
+    return { data, total };
+  }
+
+  @Get('/:id')
+  @ApiResponse({ type: FetchVO_test })
+  async fetch(@Param('id') id: string) {
+    const data = await this.service.fetch(id);
+    const result = new FetchVO_test(data);
+    return result;
+  }
+
+  @Post('/:id')
+  @Validate()
+  @ApiResponse({ type: UpdateVO_test })
+  async update(@Param('id') id: string, @Body() body: UpdateDTO_test) {
+    const result = await this.service.updateOne(id, body);
+    return result;
+  }
+
+  @Del('/:id')
+  @Validate()
+  async delete(@Param('id') id: string) {
+    await this.service.delete(id);
+    return 'ok';
+  }
+  async createMany(...args: any[]) {
+    throw new Error('Method not implemented.');
+  }
+
+  async updateMany(...args: any[]) {
+    throw new Error('Method not implemented.');
+  }
+
+  async deleteMany(...args: any[]) {
+    throw new Error('Method not implemented.');
+  }
+}

+ 15 - 0
src/entity/test.entity.ts

@@ -0,0 +1,15 @@
+import { modelOptions, prop } from '@typegoose/typegoose';
+import { BaseModel } from 'free-midway-component';
+@modelOptions({
+  schemaOptions: { collection: 'test' },
+})
+export class Test extends BaseModel {
+  @prop({ required: false, index: true, zh: '姓名' })
+  name: string;
+  @prop({ required: false, index: true, zh: '性别', remark: '0:男;1:女;2:未知', default: '0' })
+  gender: string;
+  @prop({ required: false, index: true, zh: '年龄' })
+  age: string;
+  @prop({ required: false, index: false, zh: '手机号' })
+  phone: string;
+}

+ 64 - 0
src/interface/test.interface.ts

@@ -0,0 +1,64 @@
+import { Rule, RuleType } from '@midwayjs/validate';
+import { ApiProperty } from '@midwayjs/swagger';
+import _ = require('lodash');
+import { SearchBase } from 'free-midway-component';
+export class FetchVO_test {
+  constructor(data: object) {
+    for (const key of Object.keys(this)) {
+      this[key] = _.get(data, key);
+    }
+  }
+  @ApiProperty({ description: '数据id' })
+  _id: string = undefined;
+  @ApiProperty({ description: '姓名' })
+  'name': string = undefined;
+  @ApiProperty({ description: '性别' })
+  'gender': string = undefined;
+  @ApiProperty({ description: '年龄' })
+  'age': string = undefined;
+  @ApiProperty({ description: '手机号' })
+  'phone': string = undefined;
+}
+
+export class QueryDTO_test extends SearchBase {
+  constructor() {
+    const like_prop = [];
+    const props = ['name', 'gender', 'age','phone'];
+    super({ like_prop, props });
+  }
+  @ApiProperty({ description: '姓名' })
+  'name': string = undefined;
+  @ApiProperty({ description: '性别' })
+  'gender': string = undefined;
+  @ApiProperty({ description: '年龄' })
+  'age': string = undefined;
+  @ApiProperty({ description: '手机号' })
+  'phone': string = undefined;
+}
+
+export class QueryVO_test extends FetchVO_test { }
+
+export class CreateDTO_test {
+  @ApiProperty({ description: '姓名' })
+  @Rule(RuleType['string']().empty(''))
+  'name': string = undefined;
+  @ApiProperty({ description: '性别' })
+  @Rule(RuleType['string']().empty(''))
+  'gender': string = undefined;
+  @ApiProperty({ description: '年龄' })
+  @Rule(RuleType['string']().empty(''))
+  'age': string = undefined;
+  @ApiProperty({ description: '手机号' })
+  @Rule(RuleType['string']().empty(''))
+  'phone': string = undefined;
+}
+
+export class CreateVO_test extends FetchVO_test { }
+
+export class UpdateDTO_test extends CreateDTO_test {
+  @ApiProperty({ description: '数据id' })
+  @Rule(RuleType['string']().empty(''))
+  _id: string = undefined;
+}
+
+export class UpdateVO_test extends FetchVO_test { }

+ 7 - 6
src/middleware/report.middleware.ts

@@ -1,8 +1,13 @@
-import { Middleware, IMiddleware } from '@midwayjs/core';
+import { IMiddleware } from '@midwayjs/core';
+import { Middleware, Inject } from '@midwayjs/decorator';
 import { NextFunction, Context } from '@midwayjs/koa';
+// import get = require('lodash/get');
+import { JwtService } from '@midwayjs/jwt';
 
 @Middleware()
 export class ReportMiddleware implements IMiddleware<Context, NextFunction> {
+  @Inject()
+  jwtService: JwtService;
   resolve() {
     return async (ctx: Context, next: NextFunction) => {
       // 控制器前执行的逻辑
@@ -11,11 +16,7 @@ export class ReportMiddleware implements IMiddleware<Context, NextFunction> {
       // 这里可以拿到下一个中间件或者控制器的返回值
       const result = await next();
       // 控制器之后执行的逻辑
-      ctx.logger.info(
-        `Report in "src/middleware/report.middleware.ts", rt = ${
-          Date.now() - startTime
-        }ms`
-      );
+      ctx.logger.info(`Report in "src/middleware/report.middleware.ts", rt = ${Date.now() - startTime}ms`);
       // 返回给上一个中间件的结果
       return result;
     };

+ 11 - 0
src/service/test.service.ts

@@ -0,0 +1,11 @@
+import { Provide } from '@midwayjs/decorator';
+import { InjectEntityModel } from '@midwayjs/typegoose';
+import { ReturnModelType } from '@typegoose/typegoose';
+import { BaseService } from 'free-midway-component';
+import { Test } from '../entity/test.entity';
+type modelType = ReturnModelType<typeof Test>;
+@Provide()
+export class TestService extends BaseService<modelType> {
+  @InjectEntityModel(Test)
+  model: modelType;
+}