@cicctencent/midwayjs-base 1.0.44 → 1.0.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -123,6 +123,19 @@ exports.default = (appInfo) => {
123
123
  manager: ['admin'],
124
124
  appId: appInfo.appId,
125
125
  url: process.env.BASE_SERVER_URL || '',
126
+ servant: process.env.BASE_SERVICE_SERVANT || '',
127
+ local: process.env.BASE_SERVICE_LOCAL_PORT
128
+ ? {
129
+ host: process.env.BASE_SERVICE_LOCAL_HOST || '127.0.0.1',
130
+ port: process.env.BASE_SERVICE_LOCAL_PORT,
131
+ }
132
+ : null,
133
+ serverProtocol: 'http://'
134
+ },
135
+ tars: {
136
+ client: process.env.TARS_CLIENT_LOCATOR
137
+ ? { locator: process.env.TARS_CLIENT_LOCATOR }
138
+ : null,
126
139
  },
127
140
  session: {
128
141
  timeout: Number(process.env.SESSION_TIMEOUT) || 20 * 60 * 1000,
@@ -7,6 +7,11 @@ export declare class AuthGuard implements IGuard<Context> {
7
7
  ssoOption: any;
8
8
  authOption: {
9
9
  ignores?: string | Array<RegExp | string>;
10
+ loginUrl?: string;
11
+ redirectParam?: string;
12
+ appIdParam?: string;
13
+ authCodeParam?: string | false;
14
+ cleanParams?: string[];
10
15
  };
11
16
  apiOption: any;
12
17
  koa: any;
@@ -61,13 +61,17 @@ let AuthGuard = class AuthGuard {
61
61
  let errRes = null;
62
62
  let session = null;
63
63
  try {
64
- const authCode = context.URL.searchParams.get('auth_code');
65
- if (authCode) {
64
+ const authCodeParam = this.authOption?.authCodeParam === false
65
+ ? false
66
+ : this.authOption?.authCodeParam || 'auth_code';
67
+ const authCode = authCodeParam ? context.URL.searchParams.get(authCodeParam) : null;
68
+ if (authCode && authCodeParam) {
66
69
  session = await this.sessionService.loginByCode(authCode);
67
70
  if (session) {
68
71
  (0, utils_1.setAuthToken)(context, session.id);
69
72
  }
70
- context.URL.searchParams.delete('auth_code');
73
+ if (authCodeParam)
74
+ context.URL.searchParams.delete(authCodeParam);
71
75
  context.URL.hostname = context.detect?.HOSTNAME || context.hostname;
72
76
  context.redirect(context.URL.toString());
73
77
  return;
@@ -124,17 +128,24 @@ let AuthGuard = class AuthGuard {
124
128
  throw new error_code_1.BizError(error.ret, error.msg);
125
129
  }
126
130
  else {
127
- const loginUrl = `${this.ssoOption?.baseUrl || this.koa?.globalPrefix || ''}/login`;
128
- if (!/\/login\/?(\?|$|#)/.test(context.URL.pathname)) {
129
- const URL = context.URL;
130
- if (context.detect?.HOSTNAME && URL.hostname !== context.detect.HOSTNAME) {
131
- URL.hostname = context.detect.HOSTNAME;
131
+ const loginUrl = this.authOption?.loginUrl || `${this.ssoOption?.baseUrl || this.koa?.globalPrefix || ''}/login`;
132
+ const loginPath = new URL(loginUrl, `${context.protocol}://${context.host}`).pathname;
133
+ if (context.URL.pathname !== loginPath) {
134
+ const currentUrl = context.URL;
135
+ if (context.detect?.HOSTNAME && currentUrl.hostname !== context.detect.HOSTNAME) {
136
+ currentUrl.hostname = context.detect.HOSTNAME;
132
137
  }
133
- URL.searchParams.delete('jv_auth_code');
134
- URL.searchParams.delete('token');
135
- URL.searchParams.delete('auth_code');
136
- const redirectUrl = URL.toString();
137
- context.redirect(`${loginUrl}?url=${encodeURIComponent(redirectUrl)}&appid=${this.ssoOption?.appId || 0}`);
138
+ for (const param of this.authOption?.cleanParams || ['jv_auth_code', 'token', 'auth_code']) {
139
+ currentUrl.searchParams.delete(param);
140
+ }
141
+ const redirectParam = this.authOption?.redirectParam || 'url';
142
+ const appIdParam = this.authOption?.appIdParam === undefined ? 'appid' : this.authOption.appIdParam;
143
+ const targetUrl = new URL(loginUrl, `${context.protocol}://${context.host}`);
144
+ targetUrl.searchParams.set(redirectParam, currentUrl.toString());
145
+ if (appIdParam) {
146
+ targetUrl.searchParams.set(appIdParam, String(this.ssoOption?.appId || 0));
147
+ }
148
+ context.redirect(targetUrl.toString());
138
149
  }
139
150
  else {
140
151
  context.redirect(loginUrl);
package/dist/index.d.ts CHANGED
@@ -3,6 +3,8 @@ export { BaseConfiguration as Configuration } from './configuration';
3
3
  export * as utils from './lib/utils';
4
4
  export * as jwt from './lib/jwt';
5
5
  export * as decorators from './lib/decorator';
6
+ export { default as tarsRegistry } from './lib/tarsRegistry';
7
+ export { resolveTarsEndpoint, requestTarsServer, requestWithTars, requestWithTarsApi, type TarsConfig, type RequestWithTarsOption, } from './lib/request';
6
8
  export * from '@fefeding/common/dist/models/base/enumType';
7
9
  export { BaseORM as BaseEntity } from '@fefeding/common/dist/models/base/baseORM';
8
10
  export * from './constants/error-code';
package/dist/index.js CHANGED
@@ -35,14 +35,24 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  var __exportStar = (this && this.__exportStar) || function(m, exports) {
36
36
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
37
37
  };
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
38
41
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.BaseEntity = exports.decorators = exports.jwt = exports.utils = exports.Configuration = exports.koa = void 0;
42
+ exports.BaseEntity = exports.requestWithTarsApi = exports.requestWithTars = exports.requestTarsServer = exports.resolveTarsEndpoint = exports.tarsRegistry = exports.decorators = exports.jwt = exports.utils = exports.Configuration = exports.koa = void 0;
40
43
  exports.koa = __importStar(require("@midwayjs/koa"));
41
44
  var configuration_1 = require("./configuration");
42
45
  Object.defineProperty(exports, "Configuration", { enumerable: true, get: function () { return configuration_1.BaseConfiguration; } });
43
46
  exports.utils = __importStar(require("./lib/utils"));
44
47
  exports.jwt = __importStar(require("./lib/jwt"));
45
48
  exports.decorators = __importStar(require("./lib/decorator"));
49
+ var tarsRegistry_1 = require("./lib/tarsRegistry");
50
+ Object.defineProperty(exports, "tarsRegistry", { enumerable: true, get: function () { return __importDefault(tarsRegistry_1).default; } });
51
+ var request_1 = require("./lib/request");
52
+ Object.defineProperty(exports, "resolveTarsEndpoint", { enumerable: true, get: function () { return request_1.resolveTarsEndpoint; } });
53
+ Object.defineProperty(exports, "requestTarsServer", { enumerable: true, get: function () { return request_1.requestTarsServer; } });
54
+ Object.defineProperty(exports, "requestWithTars", { enumerable: true, get: function () { return request_1.requestWithTars; } });
55
+ Object.defineProperty(exports, "requestWithTarsApi", { enumerable: true, get: function () { return request_1.requestWithTarsApi; } });
46
56
  __exportStar(require("@fefeding/common/dist/models/base/enumType"), exports);
47
57
  var baseORM_1 = require("@fefeding/common/dist/models/base/baseORM");
48
58
  Object.defineProperty(exports, "BaseEntity", { enumerable: true, get: function () { return baseORM_1.BaseORM; } });
@@ -1,2 +1,22 @@
1
1
  import { requestApi, requestServer } from '@fefeding/common/dist/utils/axios';
2
+ import type { AxiosRequestConfig, AxiosResponse } from 'axios';
3
+ import type request from '@fefeding/common/dist/models/base/request';
2
4
  export { requestApi, requestServer };
5
+ export interface TarsConfig {
6
+ servant?: string;
7
+ client?: {
8
+ locator: string;
9
+ };
10
+ local?: {
11
+ host?: string;
12
+ port?: string | number;
13
+ };
14
+ serverProtocol?: string;
15
+ }
16
+ export declare function resolveTarsEndpoint(tarsConfig: TarsConfig): Promise<string>;
17
+ export declare function requestTarsServer<T extends any>(req: request | string, tarsConfig: TarsConfig, option?: AxiosRequestConfig): Promise<AxiosResponse<any, T>>;
18
+ export interface RequestWithTarsOption extends AxiosRequestConfig {
19
+ tarsConfig?: TarsConfig;
20
+ }
21
+ export declare function requestWithTars<T extends any>(req: request | string, option?: RequestWithTarsOption): Promise<AxiosResponse<any, T>>;
22
+ export declare function requestWithTarsApi<T extends any>(req: request | string, option?: RequestWithTarsOption): Promise<T>;
@@ -1,7 +1,65 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.requestServer = exports.requestApi = void 0;
7
+ exports.resolveTarsEndpoint = resolveTarsEndpoint;
8
+ exports.requestTarsServer = requestTarsServer;
9
+ exports.requestWithTars = requestWithTars;
10
+ exports.requestWithTarsApi = requestWithTarsApi;
4
11
  const axios_1 = require("@fefeding/common/dist/utils/axios");
5
12
  Object.defineProperty(exports, "requestApi", { enumerable: true, get: function () { return axios_1.requestApi; } });
6
13
  Object.defineProperty(exports, "requestServer", { enumerable: true, get: function () { return axios_1.requestServer; } });
14
+ const tarsRegistry_1 = __importDefault(require("./tarsRegistry"));
15
+ async function resolveTarsEndpoint(tarsConfig) {
16
+ const { servant, client } = tarsConfig;
17
+ let host = '';
18
+ let port = '';
19
+ if (tarsConfig.local && tarsConfig.local.port) {
20
+ host = tarsConfig.local.host || '127.0.0.1';
21
+ port = String(tarsConfig.local.port);
22
+ }
23
+ else if (servant && client) {
24
+ const point = await tarsRegistry_1.default.getConnectPoint({ objName: servant }, client);
25
+ if (point) {
26
+ host = point.host;
27
+ port = String(point.port);
28
+ }
29
+ else {
30
+ throw { ret: -1001, msg: 'tars查询可用IP端口失败' };
31
+ }
32
+ }
33
+ else {
34
+ return '';
35
+ }
36
+ const protocol = tarsConfig.serverProtocol || 'http://';
37
+ return `${protocol}${host}:${port}`;
38
+ }
39
+ async function requestTarsServer(req, tarsConfig, option) {
40
+ const baseURL = await resolveTarsEndpoint(tarsConfig);
41
+ const res = await (0, axios_1.requestServer)(req, {
42
+ ...option,
43
+ baseURL,
44
+ });
45
+ return res;
46
+ }
47
+ async function requestWithTars(req, option) {
48
+ const { tarsConfig, ...axiosOption } = option || {};
49
+ if (tarsConfig &&
50
+ ((tarsConfig.servant && tarsConfig.client) || tarsConfig.local?.port)) {
51
+ const baseURL = await resolveTarsEndpoint(tarsConfig);
52
+ const res = await (0, axios_1.requestServer)(req, {
53
+ ...axiosOption,
54
+ baseURL,
55
+ });
56
+ return res;
57
+ }
58
+ const res = await (0, axios_1.requestServer)(req, axiosOption);
59
+ return res;
60
+ }
61
+ async function requestWithTarsApi(req, option) {
62
+ const res = await requestWithTars(req, option);
63
+ return res?.data || null;
64
+ }
7
65
  //# sourceMappingURL=request.js.map
@@ -0,0 +1,26 @@
1
+ export interface TarsEndPoint {
2
+ host: string;
3
+ port: string | number;
4
+ }
5
+ export interface TarsRegistryOptions {
6
+ objName?: string;
7
+ setName?: string;
8
+ }
9
+ export interface TarsClientConfig {
10
+ locator: string;
11
+ }
12
+ interface CachedPoints {
13
+ setName: string;
14
+ objName: string;
15
+ time: number;
16
+ endPoints: TarsEndPoint[];
17
+ }
18
+ declare function createClient(config: TarsClientConfig): any;
19
+ declare function getEndPoints(options: TarsRegistryOptions, config: TarsClientConfig): Promise<CachedPoints | undefined>;
20
+ declare function getConnectPoint(options: TarsRegistryOptions, config: TarsClientConfig): Promise<TarsEndPoint | null>;
21
+ declare const _default: {
22
+ createClient: typeof createClient;
23
+ getEndPoints: typeof getEndPoints;
24
+ getConnectPoint: typeof getConnectPoint;
25
+ };
26
+ export default _default;
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ let Registry = null;
4
+ try {
5
+ Registry = require('@tars/registry');
6
+ }
7
+ catch (e) {
8
+ }
9
+ const clients = {};
10
+ function createClient(config) {
11
+ if (!Registry) {
12
+ throw new Error('@tars/registry 未安装,请先安装该依赖:npm install @tars/registry');
13
+ }
14
+ if (clients[config.locator])
15
+ return clients[config.locator];
16
+ const registry = Registry.New();
17
+ registry.setLocator(config.locator);
18
+ return (clients[config.locator] = registry);
19
+ }
20
+ async function getEndPoints(options, config) {
21
+ const setName = options.setName || '';
22
+ const objName = options.objName || '';
23
+ const registry = createClient(config);
24
+ const cacheKey = `${objName}/${setName}`;
25
+ const cache = registry.__end_points || (registry.__end_points = {});
26
+ const points = cache[cacheKey];
27
+ if (points && points.time > Date.now() - 10000) {
28
+ return points;
29
+ }
30
+ try {
31
+ const result = {
32
+ setName,
33
+ objName,
34
+ time: Date.now(),
35
+ endPoints: [],
36
+ };
37
+ if (setName) {
38
+ const obj = await registry.findObjectByIdInSameSet(objName, setName);
39
+ result.endPoints = obj.response.arguments.activeEp.value || [];
40
+ }
41
+ else {
42
+ const obj = await registry.findObjectByIdInSameGroup(objName);
43
+ result.endPoints = obj.response.arguments.activeEp.value || [];
44
+ }
45
+ if (result.endPoints && result.endPoints.length) {
46
+ cache[cacheKey] = result;
47
+ }
48
+ else {
49
+ return points;
50
+ }
51
+ return result;
52
+ }
53
+ catch (e) {
54
+ console.log('[tarsRegistry] getEndPoints error:', e);
55
+ return points;
56
+ }
57
+ }
58
+ async function getConnectPoint(options, config) {
59
+ const points = await getEndPoints(options, config);
60
+ if (points && points.endPoints && points.endPoints.length) {
61
+ if (points.endPoints.length === 1)
62
+ return points.endPoints[0];
63
+ const index = Math.floor(points.endPoints.length * Math.random());
64
+ return points.endPoints[index] || points.endPoints[0];
65
+ }
66
+ return null;
67
+ }
68
+ exports.default = {
69
+ createClient,
70
+ getEndPoints,
71
+ getConnectPoint,
72
+ };
73
+ //# sourceMappingURL=tarsRegistry.js.map
@@ -2,6 +2,8 @@ import { Application, Context } from '@midwayjs/koa';
2
2
  import type { AxiosRequestConfig, AxiosResponse } from 'axios';
3
3
  import request from '@fefeding/common/dist/models/base/request';
4
4
  import response from '@fefeding/common/dist/models/base/response';
5
+ import { type TarsConfig, type RequestWithTarsOption } from '../lib/request';
6
+ export type { TarsConfig };
5
7
  export declare abstract class BaseService {
6
8
  protected app: Application;
7
9
  ctx: Context;
@@ -9,13 +11,23 @@ export declare abstract class BaseService {
9
11
  manager?: Array<string>;
10
12
  appId: number;
11
13
  url: string;
14
+ servant?: string;
15
+ local?: {
16
+ host?: string;
17
+ port?: string | number;
18
+ } | null;
12
19
  };
13
20
  apiOption: {
14
21
  key: string;
15
22
  };
23
+ tarsOption: {
24
+ client?: {
25
+ locator: string;
26
+ } | undefined;
27
+ };
16
28
  checkManager(account?: string): Promise<boolean | "" | undefined>;
17
29
  requestBaseApi<T extends response>(req: request | string, option?: AxiosRequestConfig): Promise<T>;
18
- requestBaseServer<T extends any>(req: request | string, option?: AxiosRequestConfig & {
30
+ requestBaseServer<T extends any>(req: request | string, option?: RequestWithTarsOption & {
19
31
  accessKey?: string;
20
32
  }): Promise<AxiosResponse<any, T>>;
21
33
  }
@@ -29,6 +29,13 @@ class BaseService {
29
29
  method: 'POST',
30
30
  baseURL: this.baseServiceOption?.url || '',
31
31
  accessKey: this.apiOption?.key || '',
32
+ tarsConfig: this.baseServiceOption?.servant
33
+ ? {
34
+ servant: this.baseServiceOption.servant,
35
+ client: this.tarsOption?.client,
36
+ local: this.baseServiceOption?.local || undefined,
37
+ }
38
+ : undefined,
32
39
  ...option,
33
40
  };
34
41
  const headers = option.headers || {};
@@ -46,7 +53,7 @@ class BaseService {
46
53
  '').toString();
47
54
  headers['x-client-ip'] = ip;
48
55
  option.headers = headers;
49
- const res = await (0, request_1.requestServer)(req, option);
56
+ const res = (await (0, request_1.requestWithTars)(req, option));
50
57
  return res;
51
58
  }
52
59
  }
@@ -67,4 +74,8 @@ __decorate([
67
74
  (0, core_1.Config)('apiOption'),
68
75
  __metadata("design:type", Object)
69
76
  ], BaseService.prototype, "apiOption", void 0);
77
+ __decorate([
78
+ (0, core_1.Config)('tars'),
79
+ __metadata("design:type", Object)
80
+ ], BaseService.prototype, "tarsOption", void 0);
70
81
  //# sourceMappingURL=base.service.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cicctencent/midwayjs-base",
3
- "version": "1.0.44",
3
+ "version": "1.0.46",
4
4
  "description": "基础框架,服务",
5
5
  "main": "dist/index.js",
6
6
  "typings": "index.d.ts",
@@ -32,7 +32,7 @@
32
32
  "@types/koa": "^3.0.3",
33
33
  "@types/lodash": "^4.17.24",
34
34
  "@types/lodash-es": "^4.17.12",
35
- "@types/node": "^24.13.0",
35
+ "@types/node": "^24.13.2",
36
36
  "cross-env": "^10.1.0",
37
37
  "jest": "^30.4.2",
38
38
  "mwts": "^1.3.0",
@@ -56,15 +56,19 @@
56
56
  "@midwayjs/static-file": "^3.20.24",
57
57
  "@midwayjs/typeorm": "^3.20.24",
58
58
  "@midwayjs/view-nunjucks": "^3.20.24",
59
- "axios": "^1.17.0",
59
+ "axios": "^1.18.1",
60
+ "browserslist": "^0.2.3",
60
61
  "dayjs": "^1.11.21",
61
62
  "dotenv": "^17.4.2",
62
63
  "ip": "^2.0.1",
63
64
  "jsonwebtoken": "^9.0.3",
64
65
  "lodash": "^4.18.1",
65
- "mysql2": "^3.22.4",
66
+ "mysql2": "^3.22.5",
66
67
  "reflect-metadata": "^0.2.2",
67
68
  "typeorm": "^0.3.30",
68
69
  "uuid": "^13.0.2"
70
+ },
71
+ "optionalDependencies": {
72
+ "@tars/registry": "^0.2.3"
69
73
  }
70
74
  }