-
Notifications
You must be signed in to change notification settings - Fork 736
Expand file tree
/
Copy pathtranslate.ts
More file actions
119 lines (116 loc) · 3.11 KB
/
Copy pathtranslate.ts
File metadata and controls
119 lines (116 loc) · 3.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import { Config, ILogger, Middleware } from '@midwayjs/core';
import { NextFunction, Context } from '@midwayjs/koa';
import { IMiddleware, Inject } from '@midwayjs/core';
import { BaseTranslateService } from '../service/translate';
import * as _ from 'lodash';
import { RESCODE } from '@cool-midway/core';
/**
* 翻译中间件
*/
@Middleware()
export class BaseTranslateMiddleware
implements IMiddleware<Context, NextFunction>
{
@Inject()
baseTranslateService: BaseTranslateService;
@Inject()
logger: ILogger;
@Config('cool.i18n')
config: {
/** 是否开启 */
enable: boolean;
/** 语言 */
languages: string[];
/** 翻译服务 */
serviceUrl?: string;
};
resolve() {
return async (ctx, next: NextFunction) => {
const url = ctx.url;
const language = ctx.get('language');
let data;
try {
data = await next();
} catch (error) {
this.logger.error(error);
// 处理翻译消息
if (error.name == 'CoolCommException') {
if (error.message && error.message !== 'success') {
ctx.status = error.statusCode || 200;
ctx.body = {
code: RESCODE.COMMFAIL,
message: await this.baseTranslateService.translate(
'msg',
language,
error.message
),
};
return;
}
}
ctx.status = error.statusCode || 200;
ctx.body = {
code: error.status || RESCODE.COMMFAIL,
message: error.message,
};
return;
}
if (!this.config.enable) {
return;
}
// 处理菜单翻译
if (url == '/admin/base/comm/permmenu') {
for (const menu of data.data.menus) {
if (menu.name) {
menu.name = await this.baseTranslateService.translate(
'menu',
language,
menu.name
);
}
}
}
if (url == '/admin/base/sys/menu/list') {
for (const menu of data.data) {
if (menu.name) {
menu.name = await this.baseTranslateService.translate(
'menu',
language,
menu.name
);
}
}
}
// 处理字典翻译
if (url == '/admin/dict/info/list') {
for (const dict of data.data) {
dict.name = await this.baseTranslateService.translate(
'dict:info',
language,
dict.name
);
}
}
if (url == '/admin/dict/type/page') {
for (const dict of data.data.list) {
dict.name = await this.baseTranslateService.translate(
'dict:type',
language,
dict.name
);
}
}
if (url == '/admin/dict/info/data' || url == '/app/dict/info/data') {
for (const key in data.data) {
for (const item of data.data[key]) {
item.name = await this.baseTranslateService.translate(
'dict:info',
language,
item.name
);
}
}
}
};
}
}