configuration.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { Configuration, App, Inject } from '@midwayjs/decorator';
  2. import * as koa from '@midwayjs/koa';
  3. import * as validate from '@midwayjs/validate';
  4. import * as info from '@midwayjs/info';
  5. import { join } from 'path';
  6. import * as FreeFrame from 'free-midway-component';
  7. // api文档
  8. import * as swagger from '@midwayjs/swagger';
  9. import * as redis from '@midwayjs/redis';
  10. import * as jwt from '@midwayjs/jwt';
  11. import { CheckTokenMiddleware } from './middleware/checkToken.middleware';
  12. import * as axios from '@midwayjs/axios';
  13. import { ILifeCycle, IMidwayContainer } from '@midwayjs/core';
  14. import { FrameworkErrorEnum, ServiceError } from 'free-midway-component';
  15. import * as rabbitmq from '@midwayjs/rabbitmq';
  16. import { Context } from '@midwayjs/koa';
  17. const axiosResponse = response => {
  18. if (response.status === 200) return response.data;
  19. else {
  20. console.log(JSON.stringify(response));
  21. throw new ServiceError('请求失败', FrameworkErrorEnum.SERVICE_FAULT);
  22. }
  23. };
  24. const axiosError = error => {
  25. return Promise.reject(error);
  26. };
  27. @Configuration({
  28. imports: [
  29. FreeFrame,
  30. validate,
  31. jwt,
  32. axios,
  33. // swagger,
  34. rabbitmq,
  35. {
  36. component: swagger,
  37. enabledEnvironment: ['local'],
  38. },
  39. {
  40. component: info,
  41. enabledEnvironment: ['local'],
  42. },
  43. redis,
  44. ],
  45. importConfigs: [join(__dirname, './config')],
  46. })
  47. export class ContainerLifeCycle implements ILifeCycle {
  48. @App()
  49. app: koa.Application;
  50. @Inject()
  51. ctx: Context;
  52. async onReady(container: IMidwayContainer) {
  53. this.app.getMiddleware().insertFirst(CheckTokenMiddleware);
  54. // base 添加头设置
  55. const httpServiceFactory = await container.getAsync(axios.HttpServiceFactory);
  56. const baseAxios = httpServiceFactory.get('base');
  57. baseAxios.defaults.headers.common['project'] = 'group-service';
  58. baseAxios.interceptors.response.use(axiosResponse, axiosError);
  59. const wechatAxios = httpServiceFactory.get('wechat');
  60. wechatAxios.interceptors.response.use(axiosResponse, axiosError);
  61. }
  62. }