@cicctencent/midwayjs-base 1.0.34 → 1.0.36

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.
Files changed (66) hide show
  1. package/README.md +347 -1
  2. package/dist/types/config/config.default.d.ts +3 -0
  3. package/dist/types/config/config.default.js +171 -0
  4. package/dist/types/config/env.js +52 -0
  5. package/dist/{configuration.js → types/configuration.js} +44 -20
  6. package/dist/{filter → types/filter}/default.filter.js +1 -2
  7. package/dist/{filter → types/filter}/notfound.filter.js +1 -3
  8. package/dist/{guard → types/guard}/api.d.ts +0 -3
  9. package/dist/types/guard/api.js +77 -0
  10. package/dist/{guard → types/guard}/auth.d.ts +0 -3
  11. package/dist/types/guard/auth.js +182 -0
  12. package/dist/{index.js → types/index.js} +27 -6
  13. package/dist/types/lib/decorator.d.ts +6 -0
  14. package/dist/types/lib/decorator.js +48 -0
  15. package/dist/types/lib/jwt.d.ts +34 -0
  16. package/dist/types/lib/jwt.js +59 -0
  17. package/dist/{lib → types/lib}/request.d.ts +0 -5
  18. package/dist/{lib → types/lib}/request.js +1 -1
  19. package/dist/{lib → types/lib}/utils.d.ts +1 -7
  20. package/dist/types/lib/utils.js +78 -0
  21. package/dist/types/middleware/apiResultFormatter.d.ts +7 -0
  22. package/dist/types/middleware/apiResultFormatter.js +83 -0
  23. package/dist/types/middleware/detect.middleware.d.ts +4 -0
  24. package/dist/types/middleware/detect.middleware.js +58 -0
  25. package/dist/types/middleware/requestInit.d.ts +7 -0
  26. package/dist/types/middleware/requestInit.js +139 -0
  27. package/dist/types/service/session.service.d.ts +9 -0
  28. package/dist/types/service/session.service.js +56 -0
  29. package/dist/types/service/tencent.service.d.ts +37 -0
  30. package/dist/types/service/tencent.service.js +132 -0
  31. package/dist/types/{base.controller.js → types/base.controller.js} +1 -4
  32. package/dist/types/{base.model.service.d.ts → types/base.model.service.d.ts} +1 -9
  33. package/dist/types/types/base.model.service.js +76 -0
  34. package/dist/types/{base.service.d.ts → types/base.service.d.ts} +1 -10
  35. package/dist/types/types/base.service.js +70 -0
  36. package/dist/types/{session.service.interface.d.ts → types/session.service.interface.d.ts} +1 -15
  37. package/dist/types/{session.service.interface.js → types/session.service.interface.js} +1 -5
  38. package/package.json +4 -1
  39. package/dist/config/config.default.d.ts +0 -3
  40. package/dist/config/config.default.js +0 -160
  41. package/dist/config/env.js +0 -19
  42. package/dist/guard/api.js +0 -88
  43. package/dist/guard/auth.js +0 -201
  44. package/dist/lib/decorator.d.ts +0 -36
  45. package/dist/lib/decorator.js +0 -79
  46. package/dist/lib/jwt.d.ts +0 -135
  47. package/dist/lib/jwt.js +0 -38
  48. package/dist/lib/utils.js +0 -88
  49. package/dist/middleware/apiResultFormatter.d.ts +0 -8
  50. package/dist/middleware/apiResultFormatter.js +0 -84
  51. package/dist/middleware/detect.middleware.d.ts +0 -5
  52. package/dist/middleware/detect.middleware.js +0 -61
  53. package/dist/middleware/requestInit.d.ts +0 -8
  54. package/dist/middleware/requestInit.js +0 -100
  55. package/dist/service/session.service.d.ts +0 -33
  56. package/dist/service/session.service.js +0 -81
  57. package/dist/service/tencent.service.d.ts +0 -45
  58. package/dist/service/tencent.service.js +0 -105
  59. package/dist/types/base.model.service.js +0 -86
  60. package/dist/types/base.service.js +0 -86
  61. /package/dist/{config → types/config}/env.d.ts +0 -0
  62. /package/dist/{configuration.d.ts → types/configuration.d.ts} +0 -0
  63. /package/dist/{filter → types/filter}/default.filter.d.ts +0 -0
  64. /package/dist/{filter → types/filter}/notfound.filter.d.ts +0 -0
  65. /package/dist/{index.d.ts → types/index.d.ts} +0 -0
  66. /package/dist/types/{base.controller.d.ts → types/base.controller.d.ts} +0 -0
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.ApiResultFormatterMiddleware = void 0;
13
+ const core_1 = require("@midwayjs/core");
14
+ const stream_1 = require("stream");
15
+ let ApiResultFormatterMiddleware = class ApiResultFormatterMiddleware {
16
+ ignore(ctx) {
17
+ const koaCtx = ctx;
18
+ if (this.apiOption?.ignore) {
19
+ for (const ig of this.apiOption.ignore) {
20
+ if (typeof ig === 'string' && koaCtx.path === ig)
21
+ return true;
22
+ if (ig?.test?.(koaCtx.path))
23
+ return true;
24
+ }
25
+ }
26
+ return false;
27
+ }
28
+ resolve() {
29
+ return async (ctx, next) => {
30
+ const koaCtx = ctx;
31
+ const isApi = this.apiOption?.reg?.test(koaCtx.request.path);
32
+ if (isApi) {
33
+ try {
34
+ await next();
35
+ const res = koaCtx.body;
36
+ if (this.canFormat(res)) {
37
+ koaCtx.body = Object.assign({
38
+ ret: 0,
39
+ msg: 'success',
40
+ data: null,
41
+ }, typeof res?.ret === 'number' ? res : { data: res });
42
+ }
43
+ }
44
+ catch (err) {
45
+ console.error(err);
46
+ if (typeof err?.ret === 'number') {
47
+ koaCtx.body = err;
48
+ }
49
+ else {
50
+ koaCtx.body = {
51
+ ret: 1001,
52
+ msg: err?.message || 'Error',
53
+ };
54
+ }
55
+ koaCtx.logger.error(koaCtx.request.rawBody, koaCtx.body);
56
+ }
57
+ finally {
58
+ if (koaCtx.status !== 302)
59
+ koaCtx.status = 200;
60
+ }
61
+ }
62
+ else {
63
+ await next();
64
+ }
65
+ };
66
+ }
67
+ canFormat(data) {
68
+ return (data !== '' &&
69
+ !Buffer.isBuffer(data) &&
70
+ !(data instanceof stream_1.Stream ||
71
+ data instanceof Uint8Array ||
72
+ data instanceof Blob));
73
+ }
74
+ };
75
+ exports.ApiResultFormatterMiddleware = ApiResultFormatterMiddleware;
76
+ __decorate([
77
+ (0, core_1.Config)('apiOption'),
78
+ __metadata("design:type", Object)
79
+ ], ApiResultFormatterMiddleware.prototype, "apiOption", void 0);
80
+ exports.ApiResultFormatterMiddleware = ApiResultFormatterMiddleware = __decorate([
81
+ (0, core_1.Middleware)()
82
+ ], ApiResultFormatterMiddleware);
83
+ //# sourceMappingURL=apiResultFormatter.js.map
@@ -0,0 +1,4 @@
1
+ import { IMiddleware, IMidwayContext } from '@midwayjs/core';
2
+ export declare class DetectMiddleware implements IMiddleware<IMidwayContext, any> {
3
+ resolve(): (ctx: IMidwayContext, next: any) => Promise<any>;
4
+ }
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.DetectMiddleware = void 0;
10
+ const core_1 = require("@midwayjs/core");
11
+ let DetectMiddleware = class DetectMiddleware {
12
+ resolve() {
13
+ return async (ctx, next) => {
14
+ const koaCtx = ctx;
15
+ const UA = koaCtx.get('user-agent') || '';
16
+ const IS_MOBILE = /Mobile/i.test(UA);
17
+ const VER_MQQ = UA.match(/QQ\/([\d.]+)/i) && UA.match(/QQ\/([\d.]+)/i)?.[1];
18
+ const IS_MQQ = Boolean(VER_MQQ);
19
+ const VER_WEIXIN = UA.match(/MicroMessenger\/([\d.]+)/i) &&
20
+ UA.match(/MicroMessenger\/([\d.]+)/i)?.[1]
21
+ .split('.')
22
+ .slice(0, 3)
23
+ .join('.');
24
+ const IS_WEIXIN = Boolean(VER_WEIXIN);
25
+ const IS_WECHATTOOLS = /wechatdevtools\//i.test(UA);
26
+ const IS_PCWEIXIN = /(Windows|Mac)Wechat/i.test(UA);
27
+ const IS_WXWORK = /wxwork\//i.test(UA);
28
+ const VER_MINA = /miniProgram/i.test(UA);
29
+ const IS_MINA = Boolean(VER_MINA);
30
+ let requestIP = (koaCtx.request.header['x-forwarded-for'] ||
31
+ koaCtx.request.ip ||
32
+ '').toString();
33
+ if (requestIP.includes(','))
34
+ requestIP = requestIP.split(',')[0];
35
+ const clientIP = (koaCtx.request.header['x-client-ip'] || requestIP).toString();
36
+ const hostname = koaCtx.get('tencent-acceleration-domain-name') ||
37
+ koaCtx.request.hostname;
38
+ koaCtx.detect = {
39
+ IS_MOBILE,
40
+ IS_MQQ,
41
+ IS_WEIXIN,
42
+ IS_WECHATTOOLS,
43
+ IS_PCWEIXIN,
44
+ IS_WXWORK,
45
+ IS_MINA,
46
+ CLIENTIP: clientIP,
47
+ REQUESTIP: requestIP,
48
+ HOSTNAME: hostname,
49
+ };
50
+ return next();
51
+ };
52
+ }
53
+ };
54
+ exports.DetectMiddleware = DetectMiddleware;
55
+ exports.DetectMiddleware = DetectMiddleware = __decorate([
56
+ (0, core_1.Middleware)()
57
+ ], DetectMiddleware);
58
+ //# sourceMappingURL=detect.middleware.js.map
@@ -0,0 +1,7 @@
1
+ import { IMiddleware, IMidwayContext } from '@midwayjs/core';
2
+ export declare class RequestInitMiddleware implements IMiddleware<IMidwayContext, any> {
3
+ loggerConfig: any;
4
+ private staticExtensions;
5
+ ignore(ctx: IMidwayContext): boolean;
6
+ resolve(): (ctx: IMidwayContext, next: any) => Promise<any>;
7
+ }
@@ -0,0 +1,139 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
19
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
23
+ };
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
41
+ var __metadata = (this && this.__metadata) || function (k, v) {
42
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
43
+ };
44
+ var __importDefault = (this && this.__importDefault) || function (mod) {
45
+ return (mod && mod.__esModule) ? mod : { "default": mod };
46
+ };
47
+ Object.defineProperty(exports, "__esModule", { value: true });
48
+ exports.RequestInitMiddleware = void 0;
49
+ const core_1 = require("@midwayjs/core");
50
+ const uuid_1 = require("uuid");
51
+ const ip = __importStar(require("ip"));
52
+ const logger_1 = __importDefault(require("@fefeding/common/dist/utils/logger"));
53
+ let RequestInitMiddleware = class RequestInitMiddleware {
54
+ constructor() {
55
+ this.staticExtensions = [
56
+ '.js',
57
+ '.css',
58
+ '.jpg',
59
+ '.png',
60
+ '.ico',
61
+ '.svg',
62
+ '.woff',
63
+ '.woff2',
64
+ '.ttf',
65
+ '.eot',
66
+ '.map',
67
+ ];
68
+ }
69
+ ignore(ctx) {
70
+ const koaCtx = ctx;
71
+ const isStaticFile = this.staticExtensions.some(ext => koaCtx.path.toLowerCase().endsWith(ext));
72
+ return isStaticFile || koaCtx.path === '/' || !koaCtx.path;
73
+ }
74
+ resolve() {
75
+ return async (ctx, next) => {
76
+ const koaCtx = ctx;
77
+ const body = (koaCtx.request.body || {});
78
+ let request_id = koaCtx.URL.searchParams.get('request_id') ||
79
+ body.request_id ||
80
+ koaCtx.request.header['x-request-id'] ||
81
+ koaCtx.cookies.get('request_id', {
82
+ signed: false,
83
+ });
84
+ if (!request_id)
85
+ request_id = (0, uuid_1.v4)().replace(/-/g, '');
86
+ koaCtx.request_id = request_id;
87
+ const logger = new logger_1.default({
88
+ remoteUrl: this.loggerConfig?.remoteUrl,
89
+ serviceName: process.env.SERVICE_NAME,
90
+ logLevel: this.loggerConfig?.level,
91
+ requestId: koaCtx.request_id || '',
92
+ loginId: koaCtx.currentSession?.loginId || '',
93
+ userId: (koaCtx.currentSession?.userId || '').toString(),
94
+ clientIP: koaCtx.detect?.CLIENTIP || koaCtx.ip || '',
95
+ serverIP: ip.address() || '',
96
+ url: koaCtx.url,
97
+ });
98
+ koaCtx.logger = logger;
99
+ const startTime = Date.now();
100
+ try {
101
+ const result = await next();
102
+ const logData = {
103
+ requestId: koaCtx.request_id,
104
+ method: koaCtx.method,
105
+ status: koaCtx.status,
106
+ result,
107
+ responseTime: Date.now() - startTime,
108
+ };
109
+ if (typeof logData.result === 'string') {
110
+ logData.result = logData.result.substring(0, 500);
111
+ }
112
+ return result;
113
+ }
114
+ catch (error) {
115
+ logger.error('Request failed', {
116
+ requestId: koaCtx.request_id,
117
+ method: koaCtx.method,
118
+ url: koaCtx.href,
119
+ error: {
120
+ name: error?.name,
121
+ message: error?.message,
122
+ stack: error?.stack,
123
+ },
124
+ responseTime: Date.now() - startTime,
125
+ });
126
+ throw error;
127
+ }
128
+ };
129
+ }
130
+ };
131
+ exports.RequestInitMiddleware = RequestInitMiddleware;
132
+ __decorate([
133
+ (0, core_1.Config)('logger'),
134
+ __metadata("design:type", Object)
135
+ ], RequestInitMiddleware.prototype, "loggerConfig", void 0);
136
+ exports.RequestInitMiddleware = RequestInitMiddleware = __decorate([
137
+ (0, core_1.Middleware)()
138
+ ], RequestInitMiddleware);
139
+ //# sourceMappingURL=requestInit.js.map
@@ -0,0 +1,9 @@
1
+ import { ISessionService } from '../types/session.service.interface';
2
+ import { Session, LoginByWxReq, LoginByWxRsp, LoginByAccountReq, LoginByAccountRsp } from '@fefeding/common/dist/models/account/session';
3
+ export declare class SessionService extends ISessionService {
4
+ getLoginSession(id: string): Promise<Session | null>;
5
+ logout(id: string): Promise<any>;
6
+ loginByCode(code: string): Promise<any>;
7
+ loginByWx(loginParams: LoginByWxReq): Promise<LoginByWxRsp>;
8
+ loginByAccount(loginParams: LoginByAccountReq): Promise<LoginByAccountRsp>;
9
+ }
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.SessionService = void 0;
10
+ const core_1 = require("@midwayjs/core");
11
+ const session_service_interface_1 = require("../types/session.service.interface");
12
+ const session_1 = require("@fefeding/common/dist/models/account/session");
13
+ let SessionService = class SessionService extends session_service_interface_1.ISessionService {
14
+ async getLoginSession(id) {
15
+ const req = new session_1.GetLoginSessionReq();
16
+ req.id = id;
17
+ const res = await this.requestBaseApi(req);
18
+ return res?.data || null;
19
+ }
20
+ async logout(id) {
21
+ const req = new session_1.LogoutReq();
22
+ req.id = id;
23
+ const res = await this.requestBaseApi(req);
24
+ this.ctx.currentSession = null;
25
+ return res;
26
+ }
27
+ async loginByCode(code) {
28
+ const res = await this.requestBaseApi('/api/session/loginByAuthCode', {
29
+ data: {
30
+ code,
31
+ },
32
+ });
33
+ if (res.ret === 0)
34
+ return res.data;
35
+ return null;
36
+ }
37
+ async loginByWx(loginParams) {
38
+ const req = new session_1.LoginByWxReq();
39
+ req.fromJSON(loginParams);
40
+ const res = await this.requestBaseApi(req);
41
+ return res;
42
+ }
43
+ async loginByAccount(loginParams) {
44
+ loginParams.appId = '0';
45
+ const req = new session_1.LoginByAccountReq();
46
+ req.fromJSON(loginParams);
47
+ const res = await this.requestBaseApi(req);
48
+ return res;
49
+ }
50
+ };
51
+ exports.SessionService = SessionService;
52
+ exports.SessionService = SessionService = __decorate([
53
+ (0, core_1.Provide)(session_service_interface_1.DEFAULT_SESSION_SERVICE_KEY),
54
+ (0, core_1.Scope)(core_1.ScopeEnum.Request, { allowDowngrade: true })
55
+ ], SessionService);
56
+ //# sourceMappingURL=session.service.js.map
@@ -0,0 +1,37 @@
1
+ import * as fs from 'fs';
2
+ import { BaseService } from '../types/base.service';
3
+ interface TencentCredentialConfig {
4
+ secretId: string;
5
+ secretKey: string;
6
+ }
7
+ export declare class TencentService extends BaseService {
8
+ tencentCredentialConfig: TencentCredentialConfig | {
9
+ [client: string]: TencentCredentialConfig;
10
+ };
11
+ cosFileOption: {
12
+ [key: string]: {
13
+ Bucket: string;
14
+ Region: string;
15
+ Key?: string;
16
+ Headers?: any;
17
+ Domain?: string;
18
+ Protocol?: string;
19
+ CompatibilityMode?: boolean;
20
+ url?: string;
21
+ };
22
+ };
23
+ cosClient(name: string, option?: any): any;
24
+ uploadCosFile(key: string, filePath: string, cos?: string, headers?: {}, client?: string): Promise<{
25
+ ETag: string;
26
+ Location: string;
27
+ url?: string;
28
+ }>;
29
+ uploadCosData(key: string, body: string | fs.ReadStream | any, cos?: string, headers?: {}, client?: string): Promise<{
30
+ ETag: string;
31
+ Location: string;
32
+ url?: string;
33
+ }>;
34
+ getCosFileUrl(key: string, cos?: string, client?: string): Promise<string>;
35
+ getFile(key: string, cos?: string, client?: string): Promise<any>;
36
+ }
37
+ export {};
@@ -0,0 +1,132 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
19
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
23
+ };
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
41
+ var __metadata = (this && this.__metadata) || function (k, v) {
42
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
43
+ };
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.TencentService = void 0;
46
+ const core_1 = require("@midwayjs/core");
47
+ const fs = __importStar(require("fs"));
48
+ const url = __importStar(require("url"));
49
+ const TxCos = __importStar(require("@fefeding/common/dist/utils/txCos"));
50
+ const lodash_1 = require("lodash");
51
+ const base_service_1 = require("../types/base.service");
52
+ let TencentService = class TencentService extends base_service_1.BaseService {
53
+ cosClient(name, option) {
54
+ const config = this.tencentCredentialConfig[name] ||
55
+ this.tencentCredentialConfig;
56
+ const clientOption = {
57
+ SecretId: config.secretId,
58
+ SecretKey: config.secretKey,
59
+ CompatibilityMode: true,
60
+ };
61
+ if (option?.Domain)
62
+ clientOption.Domain = option.Domain;
63
+ if (option?.Protocol)
64
+ clientOption.Protocol = option.Protocol;
65
+ if (option?.CompatibilityMode !== undefined)
66
+ clientOption.CompatibilityMode = option.CompatibilityMode;
67
+ const client = TxCos.createClient(clientOption);
68
+ return client;
69
+ }
70
+ async uploadCosFile(key, filePath, cos = 'default', headers = {}, client = 'default') {
71
+ const body = fs.createReadStream(filePath);
72
+ return this.uploadCosData(key, body, cos, headers, client);
73
+ }
74
+ async uploadCosData(key, body, cos = 'default', headers = {}, client = 'default') {
75
+ const option = this.cosFileOption[cos];
76
+ if ((0, lodash_1.isPlainObject)(body) || Array.isArray(body)) {
77
+ body = JSON.stringify(body);
78
+ }
79
+ headers = {
80
+ ...option.Headers,
81
+ ...headers,
82
+ };
83
+ const res = (await TxCos.putObject({
84
+ ...option,
85
+ Key: key,
86
+ Body: body,
87
+ Headers: headers,
88
+ }, this.cosClient(client, option)));
89
+ if (option.url) {
90
+ res.url = new url.URL(key, option.url).toString();
91
+ }
92
+ return res;
93
+ }
94
+ async getCosFileUrl(key, cos = 'default', client = 'default') {
95
+ if (!key) {
96
+ throw Error('指定文件地址');
97
+ }
98
+ const option = this.cosFileOption[cos];
99
+ const url = (await TxCos.getObjectUrl({
100
+ ...option,
101
+ Key: key,
102
+ Sign: true,
103
+ }, this.cosClient(client, option)));
104
+ return url;
105
+ }
106
+ async getFile(key, cos = 'default', client = 'default') {
107
+ if (!key) {
108
+ throw Error('指定文件地址');
109
+ }
110
+ const option = this.cosFileOption[cos];
111
+ const url = await TxCos.getFile({
112
+ ...option,
113
+ Key: key,
114
+ Sign: true,
115
+ }, this.cosClient(client, option));
116
+ return url;
117
+ }
118
+ };
119
+ exports.TencentService = TencentService;
120
+ __decorate([
121
+ (0, core_1.Config)('tencentCredential'),
122
+ __metadata("design:type", Object)
123
+ ], TencentService.prototype, "tencentCredentialConfig", void 0);
124
+ __decorate([
125
+ (0, core_1.Config)('tencentCosOption'),
126
+ __metadata("design:type", Object)
127
+ ], TencentService.prototype, "cosFileOption", void 0);
128
+ exports.TencentService = TencentService = __decorate([
129
+ (0, core_1.Provide)(),
130
+ (0, core_1.Scope)(core_1.ScopeEnum.Request, { allowDowngrade: true })
131
+ ], TencentService);
132
+ //# sourceMappingURL=tencent.service.js.map
@@ -10,11 +10,8 @@ var __metadata = (this && this.__metadata) || function (k, v) {
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.BaseController = void 0;
13
- // @ts-ignore
14
13
  const core_1 = require("@midwayjs/core");
15
14
  class BaseController {
16
- app;
17
- ctx;
18
15
  }
19
16
  exports.BaseController = BaseController;
20
17
  __decorate([
@@ -25,4 +22,4 @@ __decorate([
25
22
  (0, core_1.Inject)(),
26
23
  __metadata("design:type", Object)
27
24
  ], BaseController.prototype, "ctx", void 0);
28
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYmFzZS5jb250cm9sbGVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vc3JjL3R5cGVzL2Jhc2UuY29udHJvbGxlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7QUFDQSxhQUFhO0FBQ2IseUNBQTZDO0FBSTdDLE1BQXNCLGNBQWM7SUFFdEIsR0FBRyxDQUFjO0lBR2pCLEdBQUcsQ0FBVTtDQUMxQjtBQU5ELHdDQU1DO0FBSmE7SUFEVCxJQUFBLFVBQUcsR0FBRTs7MkNBQ3FCO0FBR2pCO0lBRFQsSUFBQSxhQUFNLEdBQUU7OzJDQUNjIn0=
25
+ //# sourceMappingURL=base.controller.js.map
@@ -10,17 +10,9 @@ export interface Options<Entity> {
10
10
  }
11
11
  export declare abstract class BaseModelService<K extends BaseEntity> extends BaseService {
12
12
  protected abstract model: Repository<K>;
13
- /**
14
- * 保存
15
- * @param u 对象orm
16
- */
17
13
  save(entity: K, qryRunner?: QueryRunner): Promise<K>;
18
- /** update 和 create都可以用insert */
19
14
  insert(data: DeepPartial<K> | DeepPartial<K>[]): Promise<K | K[]>;
20
- update(data: DeepPartial<K> | DeepPartial<K>[], repo?: Repository<K>): Promise<K>;
21
- /**
22
- * 删除对象
23
- */
15
+ update(data: DeepPartial<K> | DeepPartial<K>[], repo?: Repository<K>): Promise<K | K[]>;
24
16
  delete(data: DeepPartial<K> | DeepPartial<K>[], repo?: Repository<K>): Promise<K | DeepPartial<K>[]>;
25
17
  findAndCount(where: FindOptionsWhere<K> | FindOptionsWhere<K>[], options?: Options<K>): Promise<{
26
18
  rows: K[];
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BaseModelService = void 0;
4
+ const base_service_1 = require("./base.service");
5
+ const enumType_1 = require("@fefeding/common/dist/models/base/enumType");
6
+ class BaseModelService extends base_service_1.BaseService {
7
+ async save(entity, qryRunner) {
8
+ if (this.ctx?.currentSession?.loginId) {
9
+ entity.updater = this.ctx.currentSession.loginId;
10
+ }
11
+ if (qryRunner) {
12
+ return await qryRunner.manager.save(entity);
13
+ }
14
+ const res = await this.model.save(entity);
15
+ return res;
16
+ }
17
+ async insert(data) {
18
+ const isArray = Array.isArray(data);
19
+ const updater = this.ctx.currentSession?.loginId;
20
+ const entities = (isArray ? data : [data]).map(it => this.model.create({
21
+ creator: updater,
22
+ ...it,
23
+ updater,
24
+ }));
25
+ const models = await this.model.save(entities);
26
+ return isArray ? models : models[0];
27
+ }
28
+ async update(data, repo) {
29
+ let entities;
30
+ let isArray = false;
31
+ if (Array.isArray(data)) {
32
+ isArray = true;
33
+ entities = data;
34
+ }
35
+ else {
36
+ entities = [data];
37
+ }
38
+ const updater = this.ctx.currentSession?.loginId;
39
+ repo = repo || this.model;
40
+ const models = await repo.save(entities.map(o => {
41
+ return this.model.create({
42
+ ...o,
43
+ updater,
44
+ });
45
+ }));
46
+ return isArray ? models : models[0];
47
+ }
48
+ async delete(data, repo) {
49
+ repo = repo || this.model;
50
+ if (Array.isArray(data)) {
51
+ for (const m of data) {
52
+ await this.delete(m, repo);
53
+ }
54
+ return data;
55
+ }
56
+ else {
57
+ data.valid = enumType_1.EValid.Unvalid;
58
+ return await repo.save(data);
59
+ }
60
+ }
61
+ async findAndCount(where, options) {
62
+ const { select, order = { createTime: 'DESC' }, page = 1, size = 20, relations, } = options || {};
63
+ const skip = (Number(page) - 1) * Number(size);
64
+ let take = Number(size);
65
+ if (take > 10000)
66
+ take = 10000;
67
+ console.log('find count', where, skip, take);
68
+ const [rows, count] = await Promise.all([
69
+ this.model.find({ where, select, order, skip, take, relations }),
70
+ this.model.countBy(where),
71
+ ]);
72
+ return { rows, count };
73
+ }
74
+ }
75
+ exports.BaseModelService = BaseModelService;
76
+ //# sourceMappingURL=base.model.service.js.map
@@ -13,16 +13,7 @@ export declare abstract class BaseService {
13
13
  apiOption: {
14
14
  key: string;
15
15
  };
16
- /**
17
- * 是否是管理员帐号
18
- * @param account
19
- */
20
- checkManager(account?: string): Promise<boolean>;
21
- /**
22
- * 基础服务请求
23
- * @param req
24
- * @param option
25
- */
16
+ checkManager(account?: string): Promise<boolean | "" | undefined>;
26
17
  requestBaseApi<T extends response>(req: request | string, option?: AxiosRequestConfig): Promise<T>;
27
18
  requestBaseServer<T extends any>(req: request | string, option?: AxiosRequestConfig & {
28
19
  accessKey?: string;