瀏覽代碼

服务重新规划异常及i18n,见代理服务Readme

lrf 10 月之前
父節點
當前提交
f0cc791096

+ 3 - 2
src/config/config.local.ts

@@ -1,6 +1,6 @@
 import { MidwayConfig } from '@midwayjs/core';
-const ip = '120.48.146.1'; //120.48.146.1
-const redisHost = '120.48.146.1';
+const ip = '127.0.0.1'; //120.48.146.1
+const redisHost = '127.0.0.1';
 const redisPwd = '123456';
 const redisDB = 6;
 const projectDB = 'vue3js-template-test';
@@ -13,6 +13,7 @@ export default {
   koa: {
     port: 9700,
     globalPrefix: '/cxyy/api',
+    queryParseMode: 'extended',
   },
   swagger: {
     swaggerPath: '/doc/api',

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

@@ -13,6 +13,7 @@ export default {
   koa: {
     port: 9700,
     globalPrefix: '/cxyy/api',
+    queryParseMode: 'extended',
   },
   elasticsearch: {
     node: 'http://localhost:9200',

+ 4 - 4
src/configuration.ts

@@ -10,12 +10,12 @@ import * as swagger from '@midwayjs/swagger';
 import * as redis from '@midwayjs/redis';
 import { newsQueryMiddleware } from './middleware/newsQuery.middleware';
 import * as i18n from '@midwayjs/i18n';
-import { SetLocaleToCtxMiddleware } from './middleware/setLocaleToCtx.middleware';
 import * as bull from '@midwayjs/bull';
 import { ElasticsearchService } from './service/elasticsearch';
 import { DataRecordMiddleware } from './middleware/dataRecord.middleware';
 import { DBService } from './service/db.service';
 import { ReportMiddleware } from './middleware/report.middleware';
+import { CustomErrorFilter } from './filter/customError.filter';
 @Configuration({
   imports: [
     koa,
@@ -44,10 +44,10 @@ export class MainConfiguration {
   decoratorService: MidwayDecoratorService;
 
   async onReady() {
-    this.app.getMiddleware().insertFirst(SetLocaleToCtxMiddleware)
-    this.app.getMiddleware().insertAfter(DataRecordMiddleware, 'SetLocaleToCtxMiddleware');
-    this.app.getMiddleware().insertAfter(newsQueryMiddleware, 'newsQuery');
     this.app.getMiddleware().insertFirst(ReportMiddleware)
+    this.app.getMiddleware().insertAfter(DataRecordMiddleware, 'ReportMiddleware');
+    this.app.getMiddleware().insertAfter(newsQueryMiddleware, 'newsQuery');
+    this.app.useFilter([CustomErrorFilter]);
   }
   // 应用服务已启动后执行
   async onServerReady?(container: IMidwayContainer, app: IMidwayApplication) {

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

@@ -8,7 +8,7 @@ export class ESController {
 
   @Post('/async')
   async asyncData() {
-    await this.esService.asyncData();
+    // await this.esService.asyncData();
     return 'ok';
   }
 

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

@@ -1,4 +1,4 @@
-import { Controller, Get, Inject } from '@midwayjs/core';
+import { Controller, Get, Inject, httpError } from '@midwayjs/core';
 import { Context } from '@midwayjs/koa';
 import { MidwayI18nService } from '@midwayjs/i18n';
 @Controller('/')
@@ -8,9 +8,9 @@ export class HomeController {
   @Inject()
   i18n: MidwayI18nService;
 
-
   @Get('/', { description: 'ignore' })
   async home(): Promise<string> {
+    // throw new Error('LOGIN.TEST')
     return 'server starting';
   }
 }

+ 0 - 1
src/controller/login.controller.ts

@@ -7,7 +7,6 @@ import { Context } from '@midwayjs/koa';
 const assert = require('assert');
 import get = require('lodash/get');
 import { UtilService } from '../service/util.service';
-// import { FrameworkErrorEnum, ServiceError } from 'free-midway-component';
 
 @ApiTags(['登录服务'])
 @Controller('/login')

+ 4 - 4
src/controller/system/config.controller.ts

@@ -1,10 +1,10 @@
 import { Body, Controller, Del, Get, Inject, Param, Post } from '@midwayjs/decorator';
-import { BaseController, FrameworkErrorEnum, ServiceError } from 'free-midway-component';
+import { BaseController } from 'free-midway-component';
 import { ConfigService } from '../../service/system/config.service';
 import { CDTO_config, CVO_config, FVO_config, UDTO_config, UVAO_config } from '../../interface/system/config.interface';
 import { ApiResponse, ApiTags, ApiQuery } from '@midwayjs/swagger';
 import { Validate } from '@midwayjs/validate';
-import { FrameErrorEnum } from '../../error/frame.error';
+import { ServiceError, ErrorCode } from '../../error/service.error';
 import { I18nService } from '../../service/i18n.service';
 @ApiTags(['设置表'])
 @Controller('/config')
@@ -18,7 +18,7 @@ export class ConfigController extends BaseController {
   @Validate()
   @ApiResponse({ type: CVO_config })
   async create(@Body() data: CDTO_config) {
-    throw new ServiceError(this.i18n.translateError(FrameErrorEnum.SERVICE_CANT_USE), FrameErrorEnum.SERVICE_CANT_USE);
+    throw new ServiceError(ErrorCode.SERVICE_CANT_USE);
     // const dbData = await this.service.create(data);
     // const result = new CVO_config(dbData);
     // return result;
@@ -35,7 +35,7 @@ export class ConfigController extends BaseController {
   @Get('/:id')
   @ApiResponse({ type: FVO_config })
   async fetch(@Param('id') id: string) {
-    throw new ServiceError(this.i18n.translateError(FrameErrorEnum.SERVICE_CANT_USE), FrameErrorEnum.SERVICE_CANT_USE);
+    throw new ServiceError(ErrorCode.SERVICE_CANT_USE);
     // const data = await this.service.fetch(id);
     // const result = new FVO_config(data);
     // return result;

+ 0 - 1
src/controller/token.controller.ts

@@ -1,7 +1,6 @@
 import { Controller, Get, Inject } from '@midwayjs/decorator';
 import { Context } from '@midwayjs/koa';
 import { ApiResponse, ApiTags } from '@midwayjs/swagger';
-// import { TokenService } from '../service/token.service';
 const assert = require('assert');
 import { JwtService } from '@midwayjs/jwt';
 import get = require('lodash/get');

+ 0 - 14
src/error/elasticsearch.error.ts

@@ -1,14 +0,0 @@
-import { MidwayError, registerErrorCode } from '@midwayjs/core';
-
-export enum ErrorCode {
-  ES_ERROR = '-3000',
-  ES_INDEX_NOT_FOUND = '-3001',
-  ES_DATA_NOT_FOUND = '-3404'
-}
-export const EsErrorEnum = registerErrorCode('EsError', ErrorCode);
-
-export class ElasticSearchError extends MidwayError {
-  constructor(str: string, errcode: string = ErrorCode.ES_ERROR) {
-    super(str, errcode);
-  }
-}

+ 0 - 16
src/error/frame.error.ts

@@ -1,16 +0,0 @@
-import { registerErrorCode } from '@midwayjs/core';
-
-export enum ErrorCode {
-  SERVICE_ERROR = '400',
-  SERVICE_CANT_USE = '400-1',
-  NO_PERMISSION = '401',
-  USER_NOT_FOUND = '401-1',
-  BAD_PASSWORD = '401-2',
-  NOT_LOGIN = '401-3',
-  ACCOUNT_HAS_EXPIRED = '401-4',
-  ACCOUNT_LOGGED_IN_ELESWHERE = '401-5',
-  USER_IS_DISABLED = '401-6',
-  ROLE_IS_DISABLED = '401-7',
-  SERVICE_REPEAT = '401-8',
-}
-export const FrameErrorEnum = registerErrorCode('FrameError', ErrorCode);

+ 21 - 0
src/error/service.error.ts

@@ -0,0 +1,21 @@
+export enum ErrorCode {
+  SERVICE_ERROR = 'SERVICE_ERROR',
+  SERVICE_CANT_USE = 'SERVICE_CANT_USE',
+  ES_ERROR = 'ES_ERROR',
+  ES_INDEX_NOT_FOUND = 'ES_INDEX_NOT_FOUND',
+  ES_DATA_NOT_FOUND = 'ES_DATA_NOT_FOUND',
+  NOT_LOGIN = 'NOT_LOGIN',
+  ACCOUNT_HAS_EXPIRED = 'ACCOUNT_HAS_EXPIRED',
+  ACCOUNT_LOGGED_IN_ELESWHERE = 'ACCOUNT_LOGGED_IN_ELESWHERE',
+  USER_NOT_FOUND = 'USER_NOT_FOUND',
+  BAD_PASSWORD = 'BAD_PASSWORD',
+  USER_IS_DISABLED = 'USER_IS_DISABLED',
+  ROLE_IS_DISABLED = 'ROLE_IS_DISABLED',
+  SERVICE_REPEAT = 'SERVICE_REPEAT',
+}
+export class ServiceError extends Error {
+  constructor(errcode: string) {
+    super(errcode);
+    this.name = 'ServiceError';
+  }
+}

+ 16 - 0
src/filter/customError.filter.ts

@@ -0,0 +1,16 @@
+import { ApplicationContext, Catch, IMidwayContainer, Inject } from '@midwayjs/core';
+import { Context } from '@midwayjs/koa';
+import { ServiceError } from '../error/service.error';
+
+// 自定义异常
+@Catch([ServiceError])
+export class CustomErrorFilter {
+  @Inject()
+  ctx: Context;
+  @ApplicationContext()
+  applicationContext: IMidwayContainer;
+  async catch(err: Error, ctx: Context) {
+    // 接收并处理系统定义错误
+    return { errcode: err.message, stack:err.stack };
+  }
+}

+ 0 - 29
src/middleware/setLocaleToCtx.middleware.ts

@@ -1,29 +0,0 @@
-import { IMiddleware } from '@midwayjs/core';
-import { Middleware } from '@midwayjs/decorator';
-import { NextFunction, Context } from '@midwayjs/koa';
-import { head, last } from 'lodash';
-@Middleware()
-export class SetLocaleToCtxMiddleware implements IMiddleware<Context, NextFunction> {
-  resolve() {
-    return async (ctx: Context, next: NextFunction) => {
-      const cookies = ctx.request.headers.cookie;
-      try {
-        let arr = cookies.split(';');
-        arr = arr.filter(f => f.includes('locale='));
-        // 没找到locale就默认使用中文
-        if (arr.length <= 0) arr = ['locale=zh-cn'];
-        const a2 = head(arr).split('=');
-        const locale = last(a2);
-        ctx.locale = locale;
-      } catch (error) {
-        ctx.locale = 'zh-cn';
-      }
-
-      await next();
-    };
-  }
-
-  static getName(): string {
-    return 'setLocale';
-  }
-}

+ 6 - 5
src/service/elasticsearch.ts

@@ -3,7 +3,8 @@ import { Client, estypes } from '@elastic/elasticsearch';
 import { get, isArray, pick, toLower } from 'lodash';
 import { Types } from 'mongoose';
 import { GetModel } from 'free-midway-component';
-import { ElasticSearchError, EsErrorEnum } from '../error/elasticsearch.error';
+// import { ServiceError, ErrorCode } from '../error/elasticsearch.error';
+import { ServiceError, ErrorCode } from '../error/service.error';
 import { MidwayI18nService } from '@midwayjs/i18n';
 const ObjectId = Types.ObjectId;
 
@@ -199,7 +200,7 @@ export class ElasticsearchService {
     if (!this.esClient) await this.init();
     const indexName = toLower(index);
     const hasIndex = await this.esClient.indices.exists({ index: indexName });
-    if (!hasIndex) throw new ElasticSearchError(this.i18n.translate(EsErrorEnum.ES_INDEX_NOT_FOUND, { group: 'error' }), EsErrorEnum.ES_INDEX_NOT_FOUND);
+    if (!hasIndex) throw new ServiceError(ErrorCode.ES_INDEX_NOT_FOUND );
     const result = await this.esClient.update({
       index,
       id,
@@ -215,14 +216,14 @@ export class ElasticsearchService {
     if (!this.esClient) await this.init();
     const indexName = toLower(index);
     const hasIndex = await this.esClient.indices.exists({ index: indexName });
-    if (!hasIndex) throw new ElasticSearchError(this.i18n.translate(EsErrorEnum.ES_INDEX_NOT_FOUND, { group: 'error' }), EsErrorEnum.ES_INDEX_NOT_FOUND);
+    if (!hasIndex) throw new ServiceError(ErrorCode.ES_INDEX_NOT_FOUND);
     try {
       const result = await this.esClient.delete({ index: indexName, id });
       return result;
     } catch (e) {
       const code = e.statusCode;
-      if (code === 404) throw new ElasticSearchError(this.i18n.translate(EsErrorEnum.ES_DATA_NOT_FOUND, { group: 'error' }), EsErrorEnum.ES_DATA_NOT_FOUND);
-      else throw new ElasticSearchError(this.i18n.translate(EsErrorEnum.ES_ERROR, { group: 'error' }), EsErrorEnum.ES_ERROR);
+      if (code === 404) throw new ServiceError(ErrorCode.ES_DATA_NOT_FOUND);
+      else throw new ServiceError(ErrorCode.ES_ERROR);
     }
   }
   /**

+ 8 - 33
src/service/login.service.ts

@@ -1,5 +1,5 @@
 import { Config, Inject, Provide } from '@midwayjs/core';
-import { GetModel, ServiceError } from 'free-midway-component';
+import { GetModel } from 'free-midway-component';
 import { get, isEqual, upperFirst } from 'lodash';
 import { LoginDTO, LoginType, UPwdDTO } from '../interface/login.interface';
 import { RoleService } from '../service/system/role.service';
@@ -7,7 +7,7 @@ import { RedisService } from '@midwayjs/redis';
 import * as Crypto from 'crypto-js';
 import { Context } from '@midwayjs/koa';
 import { I18nService } from './i18n.service';
-import { FrameErrorEnum } from '../error/frame.error';
+import { ServiceError, ErrorCode } from '../error/service.error';
 @Provide()
 export class LoginService {
   @Inject()
@@ -39,31 +39,6 @@ export class LoginService {
     return code;
   }
 
-  async onePointCheck() {
-    const user = this.ctx.user;
-    if (!user) throw new ServiceError(this.i18n.translateError(FrameErrorEnum.NOT_LOGIN), FrameErrorEnum.NOT_LOGIN);
-    const { _id, role, login_code } = user;
-    if (!login_code) throw new ServiceError(this.i18n.translateError(FrameErrorEnum.NOT_LOGIN), FrameErrorEnum.NOT_LOGIN);
-    // 解密
-    const decodeResult = Crypto.AES.decrypt(login_code, this.jwtSecret);
-    const decode = Crypto.enc.Utf8.stringify(decodeResult).toString();
-    // 取出code
-    const codeArr = decode.split(':');
-    const code = codeArr[codeArr.length - 1];
-    // 拼接redis的key
-    const rediskey = `${this.loginSign}:${role}:${_id}`;
-    // 取出当前记录在案的 code
-    const redisCode = await this.redisService.get(rediskey);
-    if (!redisCode) throw new ServiceError(this.i18n.translateError(`${FrameErrorEnum.ACCOUNT_HAS_EXPIRED}`), FrameErrorEnum.ACCOUNT_HAS_EXPIRED);
-    // 判断是否一致
-    if (code === redisCode) {
-      // 一致,延时
-      await this.redisService.expire(rediskey, this.jwtExpiresIn);
-    } else {
-      throw new ServiceError(this.i18n.translateError(`${FrameErrorEnum.ACCOUNT_LOGGED_IN_ELESWHERE}`), FrameErrorEnum.ACCOUNT_LOGGED_IN_ELESWHERE);
-    }
-  }
-
   /**
    * 账密登录
    * @param data 用户名和密码
@@ -73,9 +48,9 @@ export class LoginService {
   async loginByAccount(data: LoginDTO, type: LoginType) {
     const model = GetModel(upperFirst(type));
     const user = await model.findOne({ account: data.account }, '+password').lean();
-    if (!user) throw new ServiceError(this.i18n.translateError(FrameErrorEnum.USER_NOT_FOUND), FrameErrorEnum.USER_NOT_FOUND);
+    if (!user) throw new ServiceError(ErrorCode.USER_NOT_FOUND);
     await this.checkAccountCanLogin(user, type);
-    if (!isEqual(user.password.secret, data.password)) throw new ServiceError(this.i18n.translateError(FrameErrorEnum.BAD_PASSWORD), FrameErrorEnum.BAD_PASSWORD);
+    if (!isEqual(user.password.secret, data.password)) throw new ServiceError(ErrorCode.BAD_PASSWORD);
     return user;
   }
   /**
@@ -89,19 +64,19 @@ export class LoginService {
     // 其他用户需要看status是不是'1';
     if (type === 'Admin') {
       if (get(user, 'is_super') === '1') {
-        if (get(user, 'is_use') === '1') throw new ServiceError(this.i18n.translateError(FrameErrorEnum.USER_IS_DISABLED), FrameErrorEnum.USER_IS_DISABLED);
+        if (get(user, 'is_use') === '1') throw new ServiceError(ErrorCode.USER_IS_DISABLED);
       }
     } else {
-      if (get(user, 'status') !== '1') throw new ServiceError(this.i18n.translateError(FrameErrorEnum.USER_IS_DISABLED), FrameErrorEnum.USER_IS_DISABLED);
+      if (get(user, 'status') !== '1') throw new ServiceError(ErrorCode.USER_IS_DISABLED);
       const role = await this.roleService.findOne({ code: type, is_use: '0' });
-      if (!role) throw new ServiceError(this.i18n.translateError(FrameErrorEnum.ROLE_IS_DISABLED), FrameErrorEnum.ROLE_IS_DISABLED);
+      if (!role) throw new ServiceError(ErrorCode.ROLE_IS_DISABLED);
     }
   }
   // 随机密码
   async updatePwd(data: UPwdDTO, type: LoginType) {
     const model = GetModel(upperFirst(type));
     const user = await model.findById(data._id);
-    if (!user) new ServiceError(this.i18n.translateError(FrameErrorEnum.USER_NOT_FOUND), FrameErrorEnum.USER_NOT_FOUND);
+    if (!user) new ServiceError(ErrorCode.USER_NOT_FOUND);
     user.password = data.password;
     await user.save();
   }

+ 2 - 3
src/service/platform/sign.service.ts

@@ -1,5 +1,4 @@
 import { Provide, Inject } from '@midwayjs/decorator';
-import { ServiceError } from 'free-midway-component';
 import { InjectEntityModel } from '@midwayjs/typegoose';
 import { ReturnModelType } from '@typegoose/typegoose';
 import { BaseService } from 'free-midway-component';
@@ -7,7 +6,7 @@ import { Sign } from '../../entity/platform/sign.entity';
 import { Match } from '../../entity/platform/match.entity';
 import { get } from 'lodash';
 import { I18nService } from '../i18n.service';
-import { FrameErrorEnum } from '../../error/frame.error';
+import { ErrorCode, ServiceError } from '../../error/service.error';
 type modelType = ReturnModelType<typeof Sign>;
 @Provide()
 export class SignService extends BaseService<modelType> {
@@ -24,7 +23,7 @@ export class SignService extends BaseService<modelType> {
   async createExamine(data) {
     const { user, match } = data;
     const result = await this.model.findOne({ user, match }).lean();
-    if (result) throw new ServiceError(this.i18n.translateError(FrameErrorEnum.SERVICE_REPEAT), FrameErrorEnum.SERVICE_REPEAT);
+    if (result) throw new ServiceError(ErrorCode.SERVICE_REPEAT);
   }
 
   // 列表