|
@@ -6,9 +6,22 @@ import * as typegoose from '@midwayjs/typegoose';
|
|
|
import * as Typegoose from '@typegoose/typegoose';
|
|
|
import { ResponseMiddleware } from './middleware/response.middleware';
|
|
|
import { DefaultErrorFilter } from './filter/default.filter';
|
|
|
+import * as axios from '@midwayjs/axios';
|
|
|
+import { ServiceError, FrameworkErrorEnum } from './error/service.error';
|
|
|
+import { IMidwayContainer } from '@midwayjs/core';
|
|
|
+
|
|
|
+const axiosResponse = response => {
|
|
|
+ if (response.status === 200) return response.data;
|
|
|
+ else {
|
|
|
+ throw new ServiceError('请求失败', FrameworkErrorEnum.REQUEST_FAULT);
|
|
|
+ }
|
|
|
+};
|
|
|
+const axiosError = error => {
|
|
|
+ return Promise.reject(error);
|
|
|
+};
|
|
|
@Configuration({
|
|
|
namespace: 'free',
|
|
|
- imports: [koa, typegoose],
|
|
|
+ imports: [koa, typegoose, axios],
|
|
|
importConfigs: [
|
|
|
{
|
|
|
default: DefaultConfig,
|
|
@@ -21,13 +34,13 @@ export class FreeConfiguration {
|
|
|
getApiUrl() {
|
|
|
const path = this.app.getConfig()?.swagger?.swaggerPath;
|
|
|
const port = this.app.getConfig()?.koa?.port;
|
|
|
- if (path)
|
|
|
- console.log(`api文档: http://127.0.0.1:${port}${path}/index.html`);
|
|
|
+ if (path) console.log(`api文档: http://127.0.0.1:${port}${path}/index.html`);
|
|
|
}
|
|
|
- async onReady() {
|
|
|
+ async onReady(container: IMidwayContainer) {
|
|
|
// TODO something
|
|
|
this.app.getMiddleware().insertLast(ResponseMiddleware);
|
|
|
this.app.useFilter([DefaultErrorFilter]);
|
|
|
+ // typegoose设置
|
|
|
Typegoose.setGlobalOptions({
|
|
|
schemaOptions: {
|
|
|
id: true,
|
|
@@ -37,6 +50,15 @@ export class FreeConfiguration {
|
|
|
options: { allowMixed: Typegoose.Severity.ALLOW },
|
|
|
});
|
|
|
this.getApiUrl();
|
|
|
+ // axios设置
|
|
|
+ const httpServiceFactory = await container.getAsync(axios.HttpServiceFactory);
|
|
|
+ const aos: object = this.app.getConfig('axios.clients');
|
|
|
+ const keys = Object.keys(aos);
|
|
|
+ for (const key of keys) {
|
|
|
+ const a = httpServiceFactory.get(key);
|
|
|
+ a.interceptors.response.use(axiosResponse, axiosError);
|
|
|
+ }
|
|
|
+
|
|
|
console.log('free frame is ready');
|
|
|
}
|
|
|
}
|