mm_api 0.0.0-stage → 1.1.1

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.
package/lib/api.js ADDED
@@ -0,0 +1,927 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+ const Item = require('mm_machine').Mod;
4
+ const { string, date, object, file } = require("mm_helper");
5
+ const { getRet } = require('mm_ret');
6
+ const Oauth = require("./oauth.js"); // 是MM自带的身份验证机制,基于Oauth2.0,可以不使用
7
+
8
+ /**
9
+ * 加载可选依赖模块
10
+ * @param {string} id 模块标识
11
+ * @returns {object|null} 模块对象,缺失时返回null
12
+ */
13
+ function loadOptional(id) {
14
+ try {
15
+ return require(id);
16
+ } catch (err) {
17
+ return null;
18
+ }
19
+ }
20
+
21
+ const Param = loadOptional("mm_param/lib/param.js"); // 是MM自带的参数机制,可以不使用
22
+ const Sql = loadOptional("mm_sql/lib/sql.js"); // 是MM自带的sql机制,可以不使用
23
+
24
+ /** param 实例缓存(模块级,替代原全局 param 模块列表) */
25
+ const PARAM_CACHE = new Map();
26
+ /** sql 实例缓存(模块级,替代原全局 sql 模块列表) */
27
+ const SQL_CACHE = new Map();
28
+
29
+ /**
30
+ * 去除 JSON 文本中的注释(支持 // 与整块注释,不处理字符串内部)
31
+ * @param {string} text 原始文本
32
+ * @returns {string} 去除注释后的文本
33
+ */
34
+ function _stripComments(text) {
35
+ var out = "";
36
+ var in_string = false;
37
+ var in_line = false;
38
+ var in_block = false;
39
+ var quote = "";
40
+
41
+ for (var i = 0; i < text.length; i++) {
42
+ var char = text[i];
43
+ var next = text[i + 1];
44
+
45
+ if (in_line) {
46
+ if (char === "\n") {
47
+ in_line = false;
48
+ out += char;
49
+ }
50
+ continue;
51
+ }
52
+ if (in_block) {
53
+ if (char === "*" && next === "/") {
54
+ in_block = false;
55
+ i++;
56
+ }
57
+ continue;
58
+ }
59
+ if (in_string) {
60
+ out += char;
61
+ if (char === "\\") {
62
+ out += next === undefined ? "" : next;
63
+ i++;
64
+ continue;
65
+ }
66
+ if (char === quote) {
67
+ in_string = false;
68
+ }
69
+ continue;
70
+ }
71
+ if (char === '"' || char === "'") {
72
+ in_string = true;
73
+ quote = char;
74
+ out += char;
75
+ continue;
76
+ }
77
+ if (char === "/" && next === "/") {
78
+ in_line = true;
79
+ i++;
80
+ continue;
81
+ }
82
+ if (char === "/" && next === "*") {
83
+ in_block = true;
84
+ i++;
85
+ continue;
86
+ }
87
+ out += char;
88
+ }
89
+ return out;
90
+ }
91
+
92
+ /**
93
+ * 读取并解析 JSON 配置文件(自动去除注释)
94
+ * @param {string} file 配置文件绝对路径
95
+ * @returns {object} 解析后的配置对象
96
+ * @throws {Error} 文件读取或解析失败时抛出
97
+ */
98
+ function _readJsonConfig(file) {
99
+ var text = fs.readFileSync(file, "utf-8");
100
+ return JSON.parse(_stripComments(text));
101
+ }
102
+
103
+ /**
104
+ * Api接口驱动类
105
+ * @augments {Item}
106
+ * @class
107
+ */
108
+ class Api extends Item {
109
+ static config = {
110
+ // 应用名称 例如:demo_app
111
+ app: "server",
112
+ // 插件名称 例如:demo_plugin
113
+ plugin: "sys",
114
+ // 名称
115
+ name: "",
116
+ // 状态 0未启用,1启用
117
+ state: 1,
118
+ // 主脚本文件(方案B:由 add() 手动配置,替代目录扫描)
119
+ main: "./index.js",
120
+ // 驱动目录(方案B:手动配置,替代目录扫描)
121
+ dir: "",
122
+ // 路径 例如:/demo
123
+ path: "",
124
+ // 接口类型,api表示服务端数据类型,web表示网页类型,app表示第三方应用类型
125
+ type: "api",
126
+ // 请求方式, POST或GET, 为空或ALL表示都可以
127
+ method: "ALL",
128
+ // 缓存时长 (单位:秒) 默认:60秒,建议600秒
129
+ cache: 0,
130
+ // 是否用客户端缓存,即 http 304 状态
131
+ client_cache: false,
132
+ // param参数验证路径 例如: ./param.json
133
+ param_path: "",
134
+ // sql模板路径 例如: ./sql.json
135
+ sql_path: "",
136
+ // 是否验证参数
137
+ check_param: true,
138
+ // 登录token请求头键名(替代原全局 dict 中的 token 键)
139
+ token_key: "token",
140
+ // 会话缓存键前缀(替代原全局 dict 中的 session_id 键)
141
+ session_key: "mm:uuid",
142
+ // 缓存实例获取函数(可选注入,未配置则跳过缓存读写)
143
+ get_cache: null,
144
+ // oauth身份验证模型, 参考oauth文件
145
+ oauth: {
146
+ scope: true,
147
+ sign_in: false,
148
+ vip: 0,
149
+ gm: 0,
150
+ mc: 0,
151
+ user_admin: [],
152
+ user_group: [],
153
+ },
154
+ };
155
+ /**
156
+ * 构造函数
157
+ * @param {object} config 配置项
158
+ * @param {object} parent 父对象(管理器实例)
159
+ * @class
160
+ */
161
+ constructor(config, parent) {
162
+ super({ ...Api.config, ...config });
163
+
164
+ // 父级管理器引用(用于缓存、插件与默认配置回退)
165
+ this.parent = parent || null;
166
+
167
+ // 脚本加载标记(方案B:替代旧基类 isLoaded 机制)
168
+ this._loaded = false;
169
+
170
+ // 初始化运行时数据结构(原由旧基类加载流程触发)
171
+ this._preset();
172
+ }
173
+ }
174
+
175
+ /**
176
+ * 预设配置
177
+ */
178
+ Api.prototype._preset = function () {
179
+ this.save_dir = "./static/file/";
180
+ this.url_path = "/file/";
181
+
182
+ // oauth身份验证配置 + 函数
183
+ this.oauth = null;
184
+ // param参数配置 + 函数
185
+ this.param = null;
186
+ // sql模板配置 + 函数
187
+ this.sql = null;
188
+
189
+ var cg = this.config;
190
+ this._loadParam(cg.param_path);
191
+ this._loadSql(cg.sql_path);
192
+ this._loadOauth();
193
+ };
194
+
195
+ /**
196
+ * 获取驱动目录(方案B:来自手动配置的 dir,替代旧基类 getDir)
197
+ * @returns {string} 驱动目录
198
+ */
199
+ Api.prototype.getDir = function () {
200
+ return this.config.dir || __dirname;
201
+ };
202
+
203
+ /**
204
+ * 读取 JSON 配置驱动文件(自动去除注释,失败仅记录日志不抛错)
205
+ * @param {string} file 配置文件绝对路径
206
+ * @returns {object|null} 配置对象,文件不存在或解析失败返回 null
207
+ * @private
208
+ */
209
+ Api.prototype._loadJsonConfig = function (file) {
210
+ if (!fs.existsSync(file)) {
211
+ this.log("warn", "配置文件不存在", file);
212
+ return null;
213
+ }
214
+ try {
215
+ return _readJsonConfig(file);
216
+ } catch (err) {
217
+ this.log("warn", "配置解析失败", file, err.message);
218
+ return null;
219
+ }
220
+ };
221
+
222
+ /**
223
+ * 获取缓存实例(方案B:可选注入,驱动配置优先,回退父级管理器配置)
224
+ * @returns {object|null} 缓存实例;未配置返回 null
225
+ * @private
226
+ */
227
+ Api.prototype._getCache = function () {
228
+ var fn = this.config.get_cache;
229
+ if (typeof fn !== "function" && this.parent) {
230
+ fn = this.parent.config.get_cache;
231
+ }
232
+ return typeof fn === "function" ? fn() : null;
233
+ };
234
+
235
+ /**
236
+ * 设置参数对象(写入模块级缓存,替代原全局 param 模块列表)
237
+ * @param {object} param 参数对象
238
+ */
239
+ Api.prototype.updateParam = function (param) {
240
+ PARAM_CACHE.set(param.config_file, param);
241
+ };
242
+
243
+ /**
244
+ * 获取现有参数
245
+ * @param {string} file 文件名
246
+ * @returns {object} 获取的对象
247
+ */
248
+ Api.prototype.getParam = function (file) {
249
+ return PARAM_CACHE.get(file) || null;
250
+ };
251
+
252
+ /**
253
+ * 加载参数配置(方案B:读取 param.json 作为驱动配置,替代旧脚本动态加载)
254
+ * @param {string} file_path 参数文件路径
255
+ * @returns {object|null} 参数驱动实例,未配置或加载失败返回 null
256
+ */
257
+ Api.prototype._loadParam = function (file_path) {
258
+ if (!file_path || !Param) {
259
+ return null;
260
+ }
261
+ var p = file.fullname(file_path, this.getDir());
262
+ var param = this.getParam(p);
263
+ if (param) {
264
+ this.param = param;
265
+ return param;
266
+ }
267
+ var cfg = this._loadJsonConfig(p);
268
+ if (!cfg) {
269
+ return null;
270
+ }
271
+ cfg.config_file = p;
272
+ cfg.dir = path.dirname(p);
273
+ this.param = new Param(cfg, this);
274
+ this.updateParam(this.param);
275
+ return this.param;
276
+ };
277
+
278
+ /**
279
+ * 设置Sql(写入模块级缓存,替代原全局 sql 模块列表)
280
+ * @param {object} sql sql对象
281
+ * @param {string} sql.config_file 文件名
282
+ * @param {object} sql.sql sql语句
283
+ */
284
+ Api.prototype.updateSql = function (sql) {
285
+ SQL_CACHE.set(sql.config_file, sql);
286
+ };
287
+
288
+ /**
289
+ * 获取现有sql模板
290
+ * @param {string} file 文件名
291
+ * @returns {object} 获取的对象
292
+ */
293
+ Api.prototype.getSql = function (file) {
294
+ return SQL_CACHE.get(file) || null;
295
+ };
296
+
297
+ /**
298
+ * 加载sql模板配置(方案B:读取 sql.json 作为驱动配置,替代旧脚本动态加载)
299
+ * @param {string} file_path sql模板文件路径
300
+ * @returns {object|null} sql驱动实例,未配置或加载失败返回 null
301
+ */
302
+ Api.prototype._loadSql = function (file_path) {
303
+ if (!file_path || !Sql) {
304
+ return null;
305
+ }
306
+ var p = file.fullname(file_path, this.getDir());
307
+ var sql = this.getSql(p);
308
+ if (sql) {
309
+ this.sql = sql;
310
+ return sql;
311
+ }
312
+ var cfg = this._loadJsonConfig(p);
313
+ if (!cfg) {
314
+ return null;
315
+ }
316
+ cfg.name = cfg.name || this.config.name;
317
+ cfg.config_file = p;
318
+ cfg.dir = path.dirname(p);
319
+ this.sql = new Sql(cfg, this);
320
+ this.updateSql(this.sql);
321
+ return this.sql;
322
+ };
323
+
324
+ /**
325
+ * 加载身份验证配置
326
+ */
327
+ Api.prototype._loadOauth = function () {
328
+ var cg = this.config.oauth;
329
+ if (cg) {
330
+ this.oauth = new Oauth({
331
+ dir: this.getDir(),
332
+ token_key: this.config.token_key,
333
+ session_key: this.config.session_key,
334
+ get_cache: () => this._getCache(),
335
+ });
336
+ this.oauth.loadObj(cg);
337
+ }
338
+ };
339
+
340
+ /**
341
+ * 获取脚本文件完整路径
342
+ * @returns {string|null} 脚本文件路径,未配置返回null
343
+ * @private
344
+ */
345
+ Api.prototype._getScriptFile = function () {
346
+ var main = this.config.main || "";
347
+ if (!main) {
348
+ return null;
349
+ }
350
+ return file.fullname(main, this.getDir());
351
+ };
352
+
353
+ /**
354
+ * 脚本是否已加载(方案B:替代旧基类 isLoaded 机制)
355
+ * @returns {boolean} 是否已加载
356
+ */
357
+ Api.prototype.isLoaded = function () {
358
+ return this._loaded;
359
+ };
360
+
361
+ /**
362
+ * 加载主脚本文件(方案B:标准 require,替代旧基类 do("load") 与热重载模式)
363
+ * @returns {object|null} 加载的模块对象
364
+ */
365
+ Api.prototype.load = function () {
366
+ var file = this._getScriptFile();
367
+ if (!file || !fs.existsSync(file)) {
368
+ return null;
369
+ }
370
+ try {
371
+ var cs = require(file);
372
+ this._setMainMethod(cs);
373
+ return cs;
374
+ } catch (err) {
375
+ this.log("error", "加载脚本文件失败", err);
376
+ return null;
377
+ }
378
+ };
379
+
380
+ /**
381
+ * 将脚本模块成员挂到驱动实例
382
+ * @param {object} mod 模块对象
383
+ * @private
384
+ */
385
+ Api.prototype._setMainMethod = function (mod) {
386
+ if (!mod) {
387
+ return;
388
+ }
389
+ var name = this.config.func_name || "main";
390
+ if (typeof mod[name] === "function") {
391
+ this.main = mod[name];
392
+ }
393
+ for (var key in mod) {
394
+ var obj = mod[key];
395
+ if (obj !== undefined && obj !== null) {
396
+ this[key] = obj;
397
+ }
398
+ }
399
+ this._loaded = true;
400
+ };
401
+
402
+ /**
403
+ * 保存文件
404
+ * @param {object} files 上传的文件
405
+ * @param {string} files.file 上传的文件对象
406
+ * @returns {object} 返回文件路径和URL
407
+ */
408
+ Api.prototype.saveFile = function (files) {
409
+ var file;
410
+ var url;
411
+ if (files.file) {
412
+ var f = files.file;
413
+ // 安全处理文件名: 移除路径穿越字符和特殊字符
414
+ var name = f.name || f.originalFilename;
415
+ name = name.replace(/[\\/]|\.\./g, "_");
416
+ file = file.fullname("./" + name, this.save_dir);
417
+ fs.mkdirSync(path.dirname(file), { recursive: true });
418
+ // 创建写入流
419
+ var read_stream = fs.createReadStream(f.filepath);
420
+
421
+ try {
422
+ let write_stream = fs.createWriteStream(file);
423
+ read_stream.pipe(write_stream);
424
+
425
+ read_stream.on("error", (err) => {
426
+ this.log("error", "读取文件流失败", err);
427
+ write_stream.destroy();
428
+ });
429
+ write_stream.on("error", (err) => {
430
+ this.log("error", "写入文件流失败", err);
431
+ read_stream.destroy();
432
+ });
433
+
434
+ url = this.url_path + name;
435
+ } catch (err) {
436
+ this.log("error", "保存文件失败", err);
437
+ }
438
+ }
439
+ return {
440
+ file,
441
+ url,
442
+ };
443
+ };
444
+
445
+ /**
446
+ * 从数据库获取登录态(方案B:实例私有方法,替代原全局 getState 回调)
447
+ * @param {object} db 数据管理器
448
+ * @param {string} token token
449
+ * @returns {object|null} 登录态与用户信息
450
+ * @private
451
+ */
452
+ Api.prototype._getState = async function (db, token) {
453
+ var db1 = db.new("user_state", "user_id");
454
+ var state = await db1.getObj(
455
+ {
456
+ token,
457
+ },
458
+ null,
459
+ null,
460
+ false,
461
+ );
462
+ if (!state) {
463
+ return null;
464
+ }
465
+ var now = new Date();
466
+ if (date.interval(state.time_sign, now, "day") <= 30) {
467
+ db.table = "user_account";
468
+ var user = await db.getObj({
469
+ user_id: state.user_id,
470
+ });
471
+ var o = { ...user };
472
+ o.password_pay = o.password_pay ? "******" : "";
473
+ o.password = o.password ? "******" : "";
474
+ delete o.salt;
475
+ delete o.time_create;
476
+ return {
477
+ state,
478
+ user: o,
479
+ };
480
+ } else {
481
+ return null;
482
+ }
483
+ };
484
+
485
+ /**
486
+ * 获取登录态(原名 getState,因与 mm_corejs 生命周期 getState 冲突而更名)
487
+ * @param {object} ctx 请求上下文
488
+ * @param {object} db 数据管理器
489
+ * @returns {object} 执行结果
490
+ */
491
+ Api.prototype.getLoginState = async function (params, ctx, options) {
492
+ var o = await this._getUserFromSession(ctx);
493
+ if (!o) {
494
+ o = await this._getUserFromToken(params, ctx, options);
495
+ }
496
+ return this._processUserInfo(o);
497
+ };
498
+
499
+ /**
500
+ * 从 session 中获取用户信息
501
+ * @param {object} ctx 请求上下文
502
+ * @returns {object|null} 用户信息
503
+ * @private
504
+ */
505
+ Api.prototype._getUserFromSession = function (ctx) {
506
+ var u = ctx.session?.user;
507
+ if (u) {
508
+ var o = { ...u };
509
+ o.token = ctx.session.uuid;
510
+ return o;
511
+ }
512
+ return null;
513
+ };
514
+
515
+ /**
516
+ * 从 token 中获取用户信息
517
+ * @param {object} ctx 请求上下文
518
+ * @param {object} db 数据管理器
519
+ * @returns {object|null} 用户信息
520
+ * @private
521
+ */
522
+ Api.prototype._getUserFromToken = async function (params, ctx, options) {
523
+ var token = ctx.headers[this.config.token_key];
524
+ if (!token) {
525
+ return null;
526
+ }
527
+ var cache = this._getCache();
528
+ if (cache) {
529
+ var u = await cache.get(this.config.session_key + "_" + token);
530
+ if (u) {
531
+ return await this._processUserFromCache(u, ctx, options, token);
532
+ }
533
+ }
534
+ return await this._getUserFromDb(token, ctx, options);
535
+ };
536
+
537
+ /**
538
+ * 处理缓存中的用户信息
539
+ * @param {object|string} u 缓存中的用户信息
540
+ * @param {object} ctx 请求上下文
541
+ * @param {object} db 数据管理器
542
+ * @param {string} token token
543
+ * @returns {object|null} 用户信息
544
+ * @private
545
+ */
546
+ Api.prototype._processUserFromCache = async function (u, ctx, options, token) {
547
+ var o;
548
+ if (typeof u === "string") {
549
+ o = { ...string.toJson(u) };
550
+ } else if (Object.keys(u).length > 0) {
551
+ o = { ...u };
552
+ }
553
+ if (!o) {
554
+ return null;
555
+ }
556
+ if (!o.user_id) {
557
+ return await this._getUserFromDb(token, ctx, options);
558
+ }
559
+ o.token = token;
560
+ return o;
561
+ };
562
+
563
+ /**
564
+ * 从数据库中获取用户信息
565
+ * @param {string} token token
566
+ * @param {object} ctx 请求上下文
567
+ * @param {object} options 数据管理器
568
+ * @returns {object|null} 用户信息
569
+ * @private
570
+ */
571
+ Api.prototype._getUserFromDb = async function (token, ctx, options) {
572
+ var obj = await this._getState(options, token);
573
+ if (obj) {
574
+ var o = { ...obj.user };
575
+ ctx.session.user = obj.user;
576
+ o.token = ctx.session.uuid;
577
+ obj.state.token = o.token;
578
+ return o;
579
+ }
580
+ return null;
581
+ };
582
+
583
+ /**
584
+ * 处理用户信息
585
+ * @param {object|null} o 用户信息
586
+ * @returns {object|null} 处理后的用户信息
587
+ * @private
588
+ */
589
+ Api.prototype._processUserInfo = function (o) {
590
+ if (o) {
591
+ o.password_pay = o.password_pay ? "******" : "";
592
+ o.password = o.password ? "******" : "";
593
+ delete o.salt;
594
+ delete o.time_create;
595
+ }
596
+ return o;
597
+ };
598
+
599
+ /**
600
+ * 获取登录态
601
+ * @param {object} ctx 请求上下文
602
+ * @param {object} options 数据管理器
603
+ * @returns {object} 执行结果
604
+ */
605
+ Api.prototype.before = async function (params, ctx, options) {
606
+ if (this.config.oauth && this.config.oauth.sign_in) {
607
+ options.user = await this.getLoginState(params, ctx, options);
608
+ }
609
+ };
610
+
611
+ /**
612
+ * 主要函数
613
+ * @param {object} ctx 请求上下文
614
+ * @param {object} options 数据管理器
615
+ * @returns {object} 执行结果
616
+ */
617
+ Api.prototype.main = async function (params, ctx, options) {
618
+ if (this.sql) {
619
+ var req = ctx.request;
620
+ // 获取文件
621
+ if (req.files) {
622
+ var fobj = this.saveFile(req.files);
623
+ req.body.file = fobj.file;
624
+ req.body.url = fobj.url;
625
+ }
626
+ var ret = await this.sql.run(req.query, req.body, options);
627
+ return ret;
628
+ } else {
629
+ return getRet().error(10000, "接口函数未定义");
630
+ }
631
+ };
632
+
633
+ /**
634
+ * 调用函数
635
+ * @param {object} ctx 请求上下文
636
+ * @param {object} db 数据管理器
637
+ * @returns {object} 执行结果
638
+ */
639
+ Api.prototype.run = async function (params, ctx, options) {
640
+ try {
641
+ var body = await this.getCache(ctx);
642
+ if (!body) {
643
+ var req = ctx.request;
644
+ var md = this.config["method"].toLocaleUpperCase();
645
+ if (md !== req.method && md !== "ALL") {
646
+ return null;
647
+ }
648
+ await this.before(params, ctx, options);
649
+ var ret = await this.check(params, ctx, options);
650
+ if (!ret) {
651
+ try {
652
+ ret = await this.main(params, ctx, options);
653
+ } catch (err) {
654
+ this.log("error", "脚本文件错误", req.path, err);
655
+ ret = getRet().error(10000, "脚本文件错误:" + err.toString());
656
+ }
657
+ }
658
+ var res = ctx.response;
659
+ body = this.body(ret, res, req.type);
660
+ this.setCache(ctx, body, res.type);
661
+ }
662
+ } catch (err) {
663
+ this.log("error", "接口错误", ctx.path, err);
664
+ }
665
+ return body;
666
+ };
667
+
668
+ /**
669
+ * 获取缓存
670
+ * @param {object} ctx 请求上下文
671
+ * @returns {string} 响应内容
672
+ */
673
+ Api.prototype.getCache = async function (ctx) {
674
+ var cg = this.config;
675
+ if (cg.cache) {
676
+ var req = ctx.request;
677
+ if (cg.client_cache) {
678
+ var etag = req.headers["if-none-match"];
679
+ if (etag) {
680
+ var stamp = Number(etag.replace('"', "").replace('"', ""));
681
+ var cha = stamp * 1000 - Date.parse(new Date());
682
+ if (cha > 0) {
683
+ ctx.response.status = 304;
684
+ return " ";
685
+ }
686
+ }
687
+ } else {
688
+ var cache = this._getCache();
689
+ if (cache) {
690
+ var data = await cache.get("api_" + req.url);
691
+ if (data) {
692
+ var obj = JSON.parse(data);
693
+ ctx.response.type = obj.type;
694
+ return obj.body;
695
+ }
696
+ }
697
+ }
698
+ }
699
+ return null;
700
+ };
701
+
702
+ /**
703
+ * 设置缓存
704
+ * @param {object} ctx 请求上下文
705
+ * @param {object} body 正文参数
706
+ * @param {string} type 响应类型
707
+ */
708
+ Api.prototype.setCache = async function (ctx, body, type = null) {
709
+ var cg = this.config;
710
+ if (cg.cache && ctx.method === "GET") {
711
+ if (cg.client_cache) {
712
+ var age = cg.cache * 60;
713
+ ctx.set("Cache-Control", "max-age=" + age);
714
+ ctx.etag = Date.parse(new Date()) / 1000 + age;
715
+ } else {
716
+ var cache = this._getCache();
717
+ if (cache) {
718
+ var req = ctx.request;
719
+ var o = {};
720
+ o.body = body;
721
+ o.type = ctx.response.type;
722
+ cache.set("api_" + req.url, JSON.stringify(o), cg.cache * 60);
723
+ }
724
+ }
725
+ }
726
+ };
727
+
728
+ /**
729
+ * 调用函数
730
+ * @param {object} result 设置响应结果
731
+ * @param {object} res 响应器
732
+ * @param {string} t 请求类型
733
+ * @returns {string} 处理后的响应结果
734
+ */
735
+ Api.prototype.body = function (result, res, t) {
736
+ var ret = result;
737
+ var type = res.type;
738
+ if (!ret) {
739
+ return ret;
740
+ }
741
+ var tp = typeof ret;
742
+ if (tp === "object") {
743
+ type = this._handleObjectType(res, type, t);
744
+ return this._convertObject(ret, type);
745
+ } else if (tp === "string") {
746
+ ret = ret.trim();
747
+ this._handleStringType(res, type, ret);
748
+ }
749
+ return ret;
750
+ };
751
+
752
+ /**
753
+ * 处理对象类型
754
+ * @param {object} res 响应器
755
+ * @param {string} type 类型
756
+ * @param {string} t 请求类型
757
+ * @returns {string} 处理后的类型
758
+ * @private
759
+ */
760
+ Api.prototype._handleObjectType = function (res, type, t) {
761
+ var new_type = type;
762
+ if (!new_type) {
763
+ new_type = t.indexOf("xml") !== -1 ? t : "application/json; charset=utf-8";
764
+ res.type = new_type;
765
+ } else {
766
+ new_type = this._normType(new_type);
767
+ res.type = new_type;
768
+ }
769
+ return new_type;
770
+ };
771
+
772
+ /**
773
+ * 标准化类型
774
+ * @param {string} type 类型
775
+ * @returns {string} 标准化后的类型
776
+ * @private
777
+ */
778
+ Api.prototype._normType = function (type) {
779
+ if (type.indexOf("json") !== -1) {
780
+ return "application/json; charset=utf-8";
781
+ } else if (type.indexOf("html") !== -1) {
782
+ return "text/html";
783
+ } else if (type.indexOf("xml") !== -1) {
784
+ return "text/xml; charset=utf-8";
785
+ }
786
+ return "text/plain; charset=utf-8";
787
+ };
788
+
789
+ /**
790
+ * 转换对象
791
+ * @param {object} obj 对象
792
+ * @param {string} type 类型
793
+ * @returns {string} 转换后的字符串
794
+ * @private
795
+ */
796
+ Api.prototype._convertObject = function (obj, type) {
797
+ return type.indexOf("/xml") !== -1 ? object.toXml(obj) : JSON.stringify(obj);
798
+ };
799
+
800
+ /**
801
+ * 处理字符串类型
802
+ * @param {object} res 响应器
803
+ * @param {string} type 类型
804
+ * @param {string} str 字符串
805
+ * @private
806
+ */
807
+ Api.prototype._handleStringType = function (res, type, str) {
808
+ if (!type) {
809
+ if (
810
+ (str.startsWith("{") && str.endsWith("}")) ||
811
+ (str.startsWith("[") && str.endsWith("]"))
812
+ ) {
813
+ res.type = "application/json; charset=utf-8";
814
+ } else if (str.endsWith("</html>")) {
815
+ res.type = "text/html";
816
+ } else if (str.startsWith("<?xml")) {
817
+ res.type = "text/xml; charset=utf-8";
818
+ } else {
819
+ res.type = "text/plain; charset=utf-8";
820
+ }
821
+ }
822
+ };
823
+
824
+ /**
825
+ * 验证参数
826
+ * @param {object} query url参数
827
+ * @param {object} body 内容参数
828
+ * @param {string} method 方法
829
+ * @returns {object} 验证结果
830
+ */
831
+ Api.prototype.checkParam = function (query, body, method) {
832
+ if (this.param) {
833
+ var msg = this.param.check(query, body, method);
834
+ if (msg) {
835
+ var code;
836
+ if (
837
+ msg.indexOf("必须") !== -1 ||
838
+ msg.indexOf("必填") !== -1 ||
839
+ msg.indexOf("为空") !== -1
840
+ ) {
841
+ code = 30001;
842
+ } else {
843
+ code = 30002;
844
+ }
845
+ return getRet().error(code, msg);
846
+ }
847
+ }
848
+ return null;
849
+ };
850
+
851
+ /**
852
+ * 验证参数
853
+ * @param {object} params 请求参数
854
+ * @param {object} ctx 内容上下文
855
+ * @param {object} options 事件运行选项
856
+ * @returns {object} 验证结果
857
+ */
858
+ Api.prototype.check = async function (params, ctx, options) {
859
+ var error;
860
+ if (this.config.check_param) {
861
+ var req = ctx.request;
862
+ error = this.checkParam(req.query, req.body, req.method);
863
+ }
864
+ if (!error) {
865
+ error = await this.checkOauth(ctx);
866
+ if (error) {
867
+ error = {
868
+ error,
869
+ };
870
+ }
871
+ }
872
+ return error;
873
+ };
874
+
875
+ /**
876
+ * 验证身份
877
+ * @param {object} ctx 内容上下文
878
+ * @returns {object} 验证结果
879
+ */
880
+ Api.prototype.checkOauth = async function (ctx) {
881
+ var aouth = this.oauth;
882
+ if (aouth) {
883
+ return await aouth.check(ctx);
884
+ } else {
885
+ return null;
886
+ }
887
+ };
888
+
889
+ /**
890
+ * 获取插件(方案B:从父级管理器插件注册表查找,替代原全局插件池)
891
+ * @param {string} app 应用名称
892
+ * @param {string} name 插件名称
893
+ * @returns {object} 返回获取到的插件
894
+ */
895
+ Api.prototype.plugin = function (app, name) {
896
+ var l = path.sep;
897
+ var dir = this.config.dir || "";
898
+ var app_name = app || string.between(dir, "app" + l, l);
899
+ var plugin_name = name || string.between(dir, "plugin" + l, l);
900
+ var plus;
901
+ var plugins = this.parent?.plugins?.[app_name];
902
+ if (plugins) {
903
+ plus = plugins.get(plugin_name);
904
+ }
905
+ return plus;
906
+ };
907
+
908
+ /**
909
+ * 获取模型
910
+ * @param {string} type 模型类型
911
+ * @returns {object} 返回获取到的模型
912
+ */
913
+ Api.prototype.getModel = function (type) {
914
+ let model = { ...this.config };
915
+ let dir = this.getDir();
916
+ let l = path.sep;
917
+ let app_name = string.between(dir, "app" + l, l);
918
+ let plugin_name = string.between(dir, "plugin" + l, l);
919
+ let name = path.basename(dir);
920
+ model.app = app_name;
921
+ model.plugin = plugin_name;
922
+ model.name = model.name || name;
923
+ model.path = "/" + app_name + "/" + name;
924
+ return model;
925
+ };
926
+
927
+ module.exports = Api;